websockt stomp SockJS

推薦閱讀:

MDN websockt
阮一峰 WebSocket
Inspecting web sockets 控制面板查看 websocket 情況
STOMP Over WebSocket 為什么要用 STOMP 和 API
stomp-js api-docs

使用 websocket 的時(shí)候要注意瀏覽器兼容性,因此很多實(shí)踐的文章
都選擇使用 sockjs 這個(gè)庫
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 之外,還有一個(gè)聯(lián)合使用的庫 @stomp/stompjs
這是因?yàn)?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

  /*****
   * 創(chuàng)建 socket 實(shí)例
   * 使用 Stomp 協(xié)議得到 stompClient
   * stompClient 進(jìn)行連接
   * stompClient 訂閱
   * stompClient 取消訂閱
   * stompClient 斷開鏈接
   * socket 實(shí)例關(guān)閉
   */
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
  {},
  // 連接成功回調(diào)函數(shù).
  this.connectCallback,
 // 鏈接失敗 TODO
);

connectCallback () {
  if (this.stompClient.connected) {
    // 訂閱
    this.subscription = this.stompClient.subscribe(url, this.subscribeCallback);
  }
}

// 訂閱回調(diào)
subscribeCallback (res) {
  // JSON 解析
  const data = JSON.parse(res.body);
}

// 取消訂閱 
this.subscription && this.subscription.unsubscribe()

// 斷開鏈接
this.stompClient && this.stompClient.disconnect()
 
// 實(shí)例關(guān)閉
this.socketIns && this.socketIns.close();

寫完發(fā)現(xiàn)有個(gè) 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

實(shí)現(xiàn)自動連接,文檔建議給 Stomp.over 的參數(shù)傳遞一個(gè)函數(shù),函數(shù)內(nèi)返回一個(gè) websocket 的實(shí)例,類似如下代碼

this.stompClient = Stomp.over(() => {
  this.socketIns = new SockJS(`url`)
  return this.socketIns
});

但是不建議這么做,因?yàn)橄聜€(gè)主版本不支持這種寫法了,建議使用 client.webSocketFactory,變更代碼如下:

set brokerURL

import { Client } from '@stomp/stompjs'

this.stompClient = new Client({
   brokerURL: ``,
})

this.stompClient.webSocketFactory = () => {
  this.socketIns = new SockJS(`url`)
  return this.socketIns
}
// 連接回調(diào)     
this.stompClient.onConnect = this.connectCallback
// 觸發(fā)連接
this.stompClient.activate()
// 訂閱  取消訂閱  不變
// 斷開連接 deactivate 是異步方法
this.stompClient && this.stompClient.deactivate()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容