最近小編接到一項緊急任務:國外同事讓讓我三天搭建一個基於stomp 協議的websocket服務。這項服務允許用戶在切換region的時候訂閱後端對應的topic. 看完這篇文章你將瞭解什麼是stomp over websocket,如何訂閱topic,如何取消訂閱topic以及如何將rxjs 與stomp 融合
- 什麼是stomp over websocket
stomp 是一種簡單的面相文本的消息傳輸協議。而websocket是一種長鏈接
由於小編最近 有點忙,廢話不說先上代碼。後續補充理論
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { Observable, Subject } from 'rxjs'
export default class AutoConnectWebSocket {
constructor(url, headers) {
this.url = url
this.stompClient = null
this.subscriptions = new Map()
this.headers = !headers ? {} : headers
this._subscribe = this._subscribe.bind(this)
this._output = new Subject()
this.interval = null
this.connected = false
this.websocket = null
}
start() {
let { url, stompClient } = this
if (!url) {
return
}
if (!stompClient || !this.connected) {
this._connectWebsocket(url)
}
return this
}
_connectWebsocket(url) {
let socket = (this.websocket = new SockJS(url)),
stompClient = (this.stompClient = Stomp.over(socket))
stompClient.connect(
this.headers,
() => {
clearInterval(this.interval)
this.connected = true
this.interval = setInterval(() => {
stompClient.send('/app/region', {}, 'socketServer')
}, 6000)
},
error => {
this.close = true
this._output.error.call(this._output, error)
}
)
socket.onclose = () => {
//ubscribe here
}
}
_subscribe = (region, sourceType) => {
if (this.close) {
return this._output
}
return new Observable(subscriber => {
let topic = this._format(region, sourceType)
if (this.subscriptions.has(topic) && !this.close && this.connected) {
let subscribeTopic = this.stompClient.subscribe(topic, data => {
try {
let dataObj = JSON.parse(data.body)
subscriber.next(dataObj)
} catch (e) {
subscriber.error(e)
}
})
this.subscriptions.set(topic, this.subscriptions)
} else {
subscriber.next(this.stompClient.connected)
}
})
}
_unscribe(region) {
//
}
}