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ù)、二進制數(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 前端如何實現(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實現(xiàn)屁桑,stomp是一個基于websocket的協(xié)議。
stomp官方有比較詳細的使用文檔:使用 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實例
let stompClient;
// 連接配置文件
const stompConfig = {
// Typically login, passcode and vhost
// 連接頭信息,通常是認證登錄信息
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)建實例
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()
}