断网(心跳检测)
主要是利用websocket定时发送消息,当超过一定时间消息还未发送成功,浏览器的websocket会自动触发onclose方法,而此时onclose有绑定了重连函数,于是就触发websocket重新连接),
const url = 'ws://127.0.0.1:3000'
class WebSocketClass {
constructor() {
this.instance = null;
this.connect();
}
static getInstance() {
//使用单例模式,只可以被实例化一次
if (!this.instance) {
this.instance = new WebSocketClass();
}
return this.instance;
}
// 创建连接
connect() {
if('WebSocket' in window){
this.ws = new WebSocket(url)
}else if('MozWebSocket' in window){
this.ws = new MozWebSocket(url)
}
this.ws.onopen = e => {
this.heartCheck();
this.getMessage();
};
}
// 心跳
heartCheck() {
const _this = this;
// 心跳状态
this.state = setInterval(() => {
// readyState
// 0 - 表示连接尚未建立。
// 1 - 表示连接已建立,可以进行通信。
// 2 - 表示连接正在进行关闭。
// 3 - 表示连接已经关闭或者连接不能打开。
if (this.ws.readyState === 1) {
//发送消息
this.ws.send("准备好了,开始吧。。。");
} else {
this.closeHandle(); // 重新连接
console.log("状态未连接");
}
}, 60000);
}
closeHandle() {
if (this.state) {
console.log(`断开,重连websocket`);
// 清除定时器;
clearInterval(this.state);
this.connect(); // 重连
} else {
console.log(`websocket手动关闭,或者正在连接`);
}
}
// 接收信息
getMessage() {
this.ws.onmessage = e => {
if (e.data) { // 接收到消息
// 自定义全局监听事件
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: newsData
}
}))
}
};
}
// 关闭
close() {
this.ws.close();
console.log("关闭连接");
}
}
export default WebSocketClass;
调用
import WebSocketClass from "@/utils/websocket.js";
// 创建消息连接
const ws = WebSocketClass.getInstance();
在需要使用的页面中添加
mounted () {
// 添加socket通知监听
window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
// 收到消息处理
getSocketData (res) {
console.log(res)
// ...业务处理
},
后端实现 node.js
const express = require('express')
const app = express();
// 导入nodejs-websocket模块
const ws = require('nodejs-websocket')
app.get('/test', function (req, res) {
res.send('测试接口');
})
// 执行websocket连接
ws.createServer(connection => {
console.log('new connection...')
//处理客户端发送过来的消息
connection.on("text", function (data) {
console.log("接收到的客户端消息:" + data);
connection.sendText('今天加餐,想吃什么,随便点。。。。')
})
//监听关闭
connection.on("close", function (code, reason) {
console.log("Connection closed")
})
//监听异常
connection.on("error", () => {
console.log('服务异常关闭...')
})
// websocket通信端口 端口不能和服务端口一致
}).listen(3000)
app.listen(8085)