java eclipse mysql 網(wǎng)站開(kāi)發(fā)百度平臺(tái)商家app下載
WebSocket
瀏覽器通過(guò)JavaScript向服務(wù)器發(fā)出建立WebSocket鏈接的請(qǐng)求,鏈接建立后,客戶端和服務(wù)器端就可以通過(guò)TCP鏈接直接交互數(shù)據(jù)。WebSocket鏈接后可以通過(guò)send()
方法來(lái)向服務(wù)器發(fā)送數(shù)據(jù),并通過(guò)onnessage
事件來(lái)接受服務(wù)器返回的數(shù)據(jù)。
創(chuàng)建WebSocket對(duì)象
let ws = new WebSocket(server);
WebSocket參考
WebSocket - Web API 接口參考 | MDN
代碼
<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對(duì)象reconnectInterval: 3000, // 重連間隔時(shí)間(毫秒)restartWebsocket: null , // 重啟定時(shí)器heartbeatInterval: null, // 心跳定時(shí)器};},created() {if (typeof WebSocket == "undefined") {console.log("您的瀏覽器不支持WebSocket");} else {this.setupWebSocket(); // 創(chuàng)建WebSocket連接}},methods: {testSend() { // 測(cè)試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連接打開(kāi)時(shí)的處理函數(shù)this.websocket.onmessage = this.onWebSocketMessage; // 收到WebSocket消息時(shí)的處理函數(shù)this.websocket.onclose = this.onWebSocketClose; // WebSocket連接關(guān)閉時(shí)的處理函數(shù)},closeWebSocket() { // 關(guān)閉if (this.websocket) {this.websocket.close(); // 關(guān)閉WebSocket連接}},// 開(kāi)啟 WebSocket;啟動(dòng)心跳檢測(cè)onWebSocketOpen() {console.log("WebSocket connection is open");this.startHeartbeat();},// 處理從服務(wù)器接收的消息onWebSocketMessage(event) {if (event.data) {const message = JSON.parse(event.data);// 根據(jù)業(yè)務(wù)來(lái)處理數(shù)據(jù)console.log("Message from server ", message);}},// 關(guān)閉 WebSocket;停止心跳檢測(cè)onWebSocketClose() {console.log("WebSocket connection is closed");this.stopHeartbeat(); // WebSocket連接關(guān)閉時(shí),停止心跳檢測(cè)this.restartWebsocket = setTimeout(this.setupWebSocket, this.reconnectInterval); // 在一定時(shí)間后重連WebSocket},// 向服務(wù)器發(fā)送消息sendMessage(message) {if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {this.websocket.send(message); // 發(fā)送消息到WebSocket服務(wù)器}},// 開(kāi)啟心跳檢測(cè)startHeartbeat() {this.heartbeatInterval = setInterval(() => {if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {this.websocket.send(); // 發(fā)送心跳消息}}, 1000); // 每1秒發(fā)送一次心跳},// 停止心跳檢測(cè)stopHeartbeat() {if (this.heartbeatInterval) {clearInterval(this.heartbeatInterval); // 停止心跳檢測(cè)定時(shí)器}},// 停止重啟檢測(cè)stopRestartWebsocket() {if (this.restartWebsocket) {clearInterval(this.restartWebsocket); // 停止心跳檢測(cè)定時(shí)器}},},beforeDestroy() {this.stopHeartbeat() // 停止心跳this.stopRestartWebsocket() // 停止重啟this.closeWebSocket(); // 在組件銷毀前關(guān)閉WebSocket連接},
}
</script><style scoped></style>