WebSocket
瀏覽器通過JavaScript向服務(wù)器發(fā)出建立WebSocket鏈接的請求,鏈接建立后,客戶端和服務(wù)器端就可以通過TCP鏈接直接交互數(shù)據(jù)。WebSocket鏈接后可以通過send()
方法來向服務(wù)器發(fā)送數(shù)據(jù),并通過onnessage
事件來接受服務(wù)器返回的數(shù)據(jù)。文章來源:http://www.zghlxwxcb.cn/news/detail-800866.html
創(chuàng)建WebSocket對象
let ws = new WebSocket(server);
WebSocket參考
WebSocket - Web API 接口參考 | MDN文章來源地址http://www.zghlxwxcb.cn/news/detail-800866.html
代碼
<template>
<el-row class="app-container">
<el-button type="primary" @click="testSend">主要按鈕</el-button>
</el-row>
</template>
<script>
export default {
name: 'Monitoring',
data() {
return {
websocket: null, // WebSocket對象
reconnectInterval: 3000, // 重連間隔時間(毫秒)
restartWebsocket: null , // 重啟定時器
heartbeatInterval: null, // 心跳定時器
};
},
created() {
if (typeof WebSocket == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
} else {
this.setupWebSocket(); // 創(chuàng)建WebSocket連接
}
},
methods: {
testSend() { // 測試
const send = {
"keywords": "xxx",
}
this.sendMessage(JSON.stringify(send));
},
// websocket初始化
setupWebSocket() {
this.websocket = new WebSocket("ws://xxx"); // 創(chuàng)建WebSocket連接
this.websocket.onopen = this.onWebSocketOpen; // WebSocket連接打開時的處理函數(shù)
this.websocket.onmessage = this.onWebSocketMessage; // 收到WebSocket消息時的處理函數(shù)
this.websocket.onclose = this.onWebSocketClose; // WebSocket連接關(guān)閉時的處理函數(shù)
},
closeWebSocket() { // 關(guān)閉
if (this.websocket) {
this.websocket.close(); // 關(guān)閉WebSocket連接
}
},
// 開啟 WebSocket;啟動心跳檢測
onWebSocketOpen() {
console.log("WebSocket connection is open");
this.startHeartbeat();
},
// 處理從服務(wù)器接收的消息
onWebSocketMessage(event) {
if (event.data) {
const message = JSON.parse(event.data);
// 根據(jù)業(yè)務(wù)來處理數(shù)據(jù)
console.log("Message from server ", message);
}
},
// 關(guān)閉 WebSocket;停止心跳檢測
onWebSocketClose() {
console.log("WebSocket connection is closed");
this.stopHeartbeat(); // WebSocket連接關(guān)閉時,停止心跳檢測
this.restartWebsocket = setTimeout(this.setupWebSocket, this.reconnectInterval); // 在一定時間后重連WebSocket
},
// 向服務(wù)器發(fā)送消息
sendMessage(message) {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(message); // 發(fā)送消息到WebSocket服務(wù)器
}
},
// 開啟心跳檢測
startHeartbeat() {
this.heartbeatInterval = setInterval(() => {
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(); // 發(fā)送心跳消息
}
}, 1000); // 每1秒發(fā)送一次心跳
},
// 停止心跳檢測
stopHeartbeat() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval); // 停止心跳檢測定時器
}
},
// 停止重啟檢測
stopRestartWebsocket() {
if (this.restartWebsocket) {
clearInterval(this.restartWebsocket); // 停止心跳檢測定時器
}
},
},
beforeDestroy() {
this.stopHeartbeat() // 停止心跳
this.stopRestartWebsocket() // 停止重啟
this.closeWebSocket(); // 在組件銷毀前關(guān)閉WebSocket連接
},
}
</script>
<style scoped>
</style>
到了這里,關(guān)于Vue 如何使用WebSocket與服務(wù)器建立鏈接 持續(xù)保持通信的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!