推薦閱讀:
MDN websockt
阮一峰 WebSocket
Inspecting web sockets 控制面板查看 websocket 情況
STOMP Over WebSocket 為什么要用 STOMP 和 API
stomp-js api-docs
使用 websocket 的時候要注意瀏覽器兼容性,因此很多實踐的文章
都選擇使用 sockjs 這個庫
SockJS is a JavaScript library (for browsers) that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server, with WebSockets or without. This necessitates the use of a server, which this is one version of, for Node.js.
除了 sockjs 之外,還有一個聯合使用的庫 @stomp/stompjs
這是因為 WebSockets are "TCP for the Web".
In general JavaScript engines in browsers are not friendly to binary protocols, so using STOMP is a good option because it is a text-oriented protocol.
所以可在 WebSockets 上層使用 stomp(Simple (or Streaming) Text Orientated Messaging Protocol)
偽代碼,參考 STOMP Over WebSocket
/*****
* 創建 socket 實例
* 使用 Stomp 協議得到 stompClient
* stompClient 進行連接
* stompClient 訂閱
* stompClient 取消訂閱
* stompClient 斷開鏈接
* socket 實例關閉
*/
import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';
this.socketIns = new SockJS(`url`);
this.stompClient = Stomp.over(this.socketIns);
this.stompClient.connect(
// headers
{},
// 連接成功回調函數.
this.connectCallback,
// 鏈接失敗 TODO
);
connectCallback () {
if (this.stompClient.connected) {
// 訂閱
this.subscription = this.stompClient.subscribe(url, this.subscribeCallback);
}
}
// 訂閱回調
subscribeCallback (res) {
// JSON 解析
const data = JSON.parse(res.body);
}
// 取消訂閱
this.subscription && this.subscription.unsubscribe()
// 斷開鏈接
this.stompClient && this.stompClient.disconnect()
// 實例關閉
this.socketIns && this.socketIns.close();
寫完發現有個 warning
Stomp.over did not receive a factory, auto reconnect will not work. Please see https://stomp-js.github.io/api-docs/latest/classes/Stomp.html#over
實現自動連接,文檔建議給 Stomp.over
的參數傳遞一個函數,函數內返回一個 websocket 的實例,類似如下代碼
this.stompClient = Stomp.over(() => {
this.socketIns = new SockJS(`url`)
return this.socketIns
});
但是不建議這么做,因為下個主版本不支持這種寫法了,建議使用 client.webSocketFactory
,變更代碼如下:
import { Client } from '@stomp/stompjs'
this.stompClient = new Client({
brokerURL: ``,
})
this.stompClient.webSocketFactory = () => {
this.socketIns = new SockJS(`url`)
return this.socketIns
}
// 連接回調
this.stompClient.onConnect = this.connectCallback
// 觸發連接
this.stompClient.activate()
// 訂閱 取消訂閱 不變
// 斷開連接 deactivate 是異步方法
this.stompClient && this.stompClient.deactivate()