websocket及stomp.js

websocket

服務(wù)端(node)

安裝nodejs-websocket

npm i nodejs-websocket

編寫最基本的服務(wù)的代碼,可以查看文檔https://github.com/sitegui/nodejs-websocket

var ws = require("nodejs-websocket");
console.log("開始建立連接...")

var server = ws.createServer(function (conn) {
  // 這里可以監(jiān)聽文本數(shù)據(jù)、二進(jìn)制數(shù)據(jù)等
  conn.on("text", function (str) {
    console.log("message:" + str)
    conn.sendText("你好,我是服務(wù)端");
  })
  conn.on("close", function (code, reason) {
    console.log("關(guān)閉連接")
  });
  conn.on("error", function (code, reason) {
    console.log("異常關(guān)閉")
  });
}).listen(8001)
console.log("listening on *:8001")

客戶端

自html5開始,是本身支持websocket的,所以不需要引入其他第三方庫就能直接使用

參考:webSocket 前端如何實(shí)現(xiàn)_chuangshaoxia5899的博客-CSDN博客

// 
const ws = new WebSocket('ws://10.10.0.99:8001')
ws.onopen = function () {
  ws.send('你好,我是客戶端')
}

ws.onmessage = function (e) {
  console.log("接收到服務(wù)端消息" + e.data)
}

ws.onclose = function (e) {
  console.log("服務(wù)關(guān)閉");
}
ws.onerror = function () {
  console.log("連接出錯");
}

stomp.js

從上面的websocket簡單使用可以看出,websocket是非常簡單的,但是他不能像常規(guī)的http訪問一樣請求接口,我們想要按接口一樣請求不同的數(shù)據(jù),就需要使用socket.io.js或者stomp.js。

這里我們主要介紹stomp,stomp.js是一個stomp協(xié)議的js實(shí)現(xiàn),stomp是一個基于websocket的協(xié)議。

stomp官方有比較詳細(xì)的使用文檔:使用 StompJs v5+ - StompJS 系列 (stomp-js.github.io)和簡單示例samples/chat.html at master · stomp-js/samples (github.com)

客戶端使用

沒有找相關(guān)的node服務(wù)端代碼,公司服務(wù)端是由java完成的,所以這里就只介紹客戶端了

先安裝依賴 npm i @stomp/stompjs

import { Client } from '@stomp/stompjs'
mounted () {
    this.initStompData()
}
// stomp實(shí)例
let stompClient;

// 連接配置文件
const stompConfig = {
    // Typically login, passcode and vhost
    // 連接頭信息,通常是認(rèn)證登錄信息
    connectHeaders: {
        login: "guest",
        passcode: "guest"
    },

    // 連接url,應(yīng)該以 ws:// or wss:// 開頭
    brokerURL: "ws://localhost:15674/ws",

    // debug
    debug: function (str) {
        console.log('STOMP: ' + str);
    },

    // 失敗重連時間,200毫秒
    reconnectDelay: 200,

    // Subscriptions should be done inside onConnect as those need to reinstated when the broker reconnects
    // 連接成功的監(jiān)聽,訂閱應(yīng)該在他內(nèi)部完成
    onConnect: function (frame) {
        // The return object has a method called `unsubscribe`
        // 訂閱/topic/chat這個即可,返回的對象有一個unsubscribe的方法
        const subscription = stompClient.subscribe('/topic/chat', function (message) {
            const payload = JSON.parse(message.body);
            // 接收到訂閱的消息
        });
    }
}

initStompData(){
    // 創(chuàng)建實(shí)例
    stompClient = new Client(stompConfig);
    const payLoad = { user: user, message: message };
    // 向服務(wù)端/topic/chat 發(fā)送數(shù)據(jù),body只支持字符串,所以對象數(shù)據(jù)需轉(zhuǎn)成字符串發(fā)送
    // 當(dāng)然也可以通過headers發(fā)送,支持對象形式
    stompClient.publish({destination: '/topic/chat', body: JSON.stringify(payLoad)});
    // stompClient.publish({destination: '/topic/chat', headers: payLoad});
    
    // 發(fā)生錯誤的監(jiān)聽
    client.onStompError = function(frame) {
      console.info('Broker reported error:' + frame.headers['message']);
      console.info('Additional details:' + frame.body);
    }
    
    // 開啟連接
    client.activate()
}
    

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容