最近项目需求需要实现账号唯N性。同一账号允许多窗口、多台电脑登录上限。
由项目需求所得,想用websocket实现看下。以前也没正式玩过。
项目结构-login登录成功后会跳转到以main.vue为基础页面的界面上,所以我只要在main.vue页面的mounted中去创建以及在beforeDestroy中去销毁websocket基本就可以了。
因为在vue中有多个方法地方需要用到同一个websocket对象,所以我直接定义在data下。
对websocket生成写在一个方法中,并把这个方法放到mounted中调用。
/**
* 初始化websocket
*/
initWebSocket(){
// var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
var serviceIp ="172.168.0.16:8880";
this.websocket = new WebSocket("ws://"+serviceIp+"/system/websocket");
}else if ('MozWebSocket' in window) {
var serviceIp ="172.168.0.16:8880";
this.websocket = new WebSocket("ws://"+serviceIp+"/system/websocket");
}
else {
console.log('当前浏览器 Not support websocket');
let that = this;
this.interval = window.setInterval(function(){ //每隔30秒钟发送一次心跳,避免websocket连接因超时而自动断开
that.forgeWebSocket();
},30000);
}
let that = this;
this.interval = window.setInterval(function(){ //每隔30秒钟发送一次心跳,避免websocket连接因超时而自动断开
if(that.websocket!=null){
that.websocket.send("HeartBeat");
console.log("发送心跳包:HeartBeat");
}
},30000);
//连接发生错误的回调方法
this.websocket.onerror = function (ev) {
console.log("WebSocket连接发生错误");
};
//连接成功建立的回调方法
this.websocket.onopen = function (ev) {
console.log("WebSocket连接成功");
this.send("addsocket");
}
//接收到消息的回调方法
this.websocket.onmessage = function (event) {
console.log(event.data);
}
//连接关闭的回调方法
this.websocket.onclose = function (ev) {
console.log("WebSocket连接关闭");
this.websocket=null;
}
},
直接关闭浏览器窗口或者标签页时也需要关闭websocket连接,所以需要同时把下面的操作也放在mounted中
let vm = this;
window.onbeforeunload = function () {
// vm.send("closesocket:");
vm.closeWebSocket();
}
/*-----------------------------------------------------------------------**/
//发送消息
send(message){
if(this.websocket && this.websocket != null){
this.websocket.send(message);
console.log("发送的消息:"+message);
}
},
//关闭WebSocket连接
closeWebSocket() {
if(this.websocket != null){
this.websocket.close();
console.log("已执行closeWebSocket中关闭websocket操作");
}
if(this.interval){
window.clearInterval(this.interval);
console.log("清除定时器");
}
},
最后需要在beforeDestroy方法中执行closeWebSocket方法去关闭连接并清除定时器。
另外forgeWebSocket这个方法是在不支持websocket的浏览器中去执行,这个方法作用是作为最早得轮询方式去保持长连接。
这样不管浏览器支不支持websocket都能保持长连接的功能作用。
如果有不好或者不对的地方还望指出,谢谢!!!