最近在做一个后台实时通知的项目,项目中用到了socket来实现前后端建立通信,在此记录一下。
<template>
<div>
<h1>测试webSocket</h1>
<div id ="aaa" style="height: 300px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;"></div>
</div>
</template>
<script>
var that;
export default {
data(){
return {
data:0,
timeout: 30 * 1000,//30秒一次心跳
timeoutObj: null,//心跳心跳倒计时
serverTimeoutObj: null,//心跳倒计时
timeoutnum: null,//断开 重连倒计时
websocket: null,
}
},
created() { // 页面创建生命周期函数
that = this;
that.initWebSocket()
},
destroyed: function () { // 离开页面生命周期函数
that.websocketclose();
},
methods: {
initWebSocket: function () {
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
that.websocket = new WebSocket("wss://127.0.0.1:9231/kh_snmptrap/websocket/lsmsp");
that.websocket.onopen = that.websocketonopen;
that.websocket.onerror = that.websocketonerror;
that.websocket.onmessage = that.setOnmessageMessage;
that.websocket.onclose = that.websocketclose;
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
// window.onbeforeunload = that.onbeforeunload
},
reconnect: function () { // 重新连接
if(that.lockReconnect) return;
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(() => {
//新连接
that.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
reset: function () { // 重置心跳
// 清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
// 重启心跳
that.start();
},
start: function () { // 开启心跳
that.timeoutObj && clearTimeout(that.timeoutObj);
that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
that.timeoutObj = setTimeout(() => {
// 这里发送一个心跳,后端收到后,返回一个心跳消息,
if (that.websocket && that.websocket.readyState == 1) { // 如果连接正常
that.websocketsend('heartbeat');
} else { // 否则重连
that.reconnect();
}
that.serverTimeoutObj = setTimeout(() => {
//超时关闭
that.websocket.close();
}, that.timeout);
}, that.timeout)
},
setOnmessageMessage: function(event) {
let obj = JSON.parse(event.data);
// console.log("obj",obj)
switch(obj.type) {
case 'heartbeat':
//收到服务器信息,心跳重置
that.reset();
break;
case 'sendMessage':
that.data = obj.data
console.log("接收到的服务器消息:",JSON.stringify(obj.data,null,4))
document.getElementById('aaa').innerHTML=JSON.stringify(obj.data,null,4)
}
},
websocketonopen: function () {
//开启心跳
that.start();
console.log("WebSocket连接成功!!!"+new Date()+"----"+that.websocket.readyState);
},
websocketonerror: function (e) {
console.log("WebSocket连接发生错误" + e);
},
websocketonmessage: function (e) {
console.log(e.data); // console.log(e);
document.getElementById('aaa').innerHTML=e.data
},
websocketclose: function (e) {
that.websocket.close();
console.log("connection closed ");
},
websocketsend(messsage) {
that.websocket.send(messsage)
},
closeWebSocket() { // 关闭websocket
that.websocket.close()
}
}
}
</script>
<style >
</style>
还有一点,我这里是https的请求,如果你是http请求的话,把wss://127.0.0.1:8888改为ws://127.0.0.1:8888。
|