考虑到登录之后要始终连接服务器接收消息,所以把websocket实例对象作为模块抛出,在main.js中引入,使全局都可以获得ws并且使用相关方法。
由于刷新页面时,ws会自动断开连接,所以在App.vue组件挂载时再次连接服务器。
utils/websocket.js
该文件位置任意,引入的时候注意路径即可
export default {
ws: {},
setWs: function(newWs) {
this.ws = newWs
},
start(){// 发送心跳
clearInterval(this.timeoutObj)
this.timeoutObj = setInterval(() => {
if (this.ws && this.ws.readyState === 1) {
console.log('发送心跳')
this.ws.send(JSON.stringify({
//后端需要接收的数据
}));
}
}, 10 *1000)//十秒发一次
},
localSocket(userId) {//连接ws,根据连接服务器是否需要参数设置该方法是否需要接收参数
if ("WebSocket" in window) {
// console.log("您的浏览器支持 WebSocket!");
// location.host
this.ws = new WebSocket('这里要填连接服务器的地址');
this.setWs(this.ws);
this.ws.onopen = ()=>{
console.log('websocket连接成功');
//连接上之后要发心跳包
this.start()
};
this.ws.onclose = ()=> {
// 关闭 websocket
console.log("连接已关闭...");
//断线重新连接
setTimeout(() => {
this.localSocket(userId);
}, 2000);
};
} else {
// 浏览器不支持 WebSocket
console.log("您的浏览器不支持 WebSocket!");
this.openNotificationWithIcon('error', '浏览器', '您的浏览器不支持显示消息请更换', 1,1)
}
},
}
import global from '@/utils/websocket'
Vue.prototype.global = global
mounted(){
this.global.localSocket(userId)
//连上之后要接收服务器发来的消息
this.global.ws.onmessage = (msg)=>{
console.log(JSON.parse(msg.data))
}
}
第二种方法,直接写在.vue文件中
//////websocket
contactSocket() {
let webSocket = null;
let socketOpen = false;
let that = this
if ("WebSocket" in window) {
webSocket = new WebSocket("wss://10.44.166.5:81/websocket/biological/websocket");
webSocket.onopen = function () {
console.log("连接成功!");
webSocket.send({
"command": "device_status",
"time": "16655155",
"command_id": "eef10d68-86f1-4251-bdc0-76bafbf5962e",
"device_type": "fingerprint",
"data": { "figer_type": "left_hand" }
})
socketOpen = true
};
webSocket.onmessage = function (evt) {
let received_msg = evt.data;
console.log("接受消息:" + received_msg);
};
webSocket.onclose = function () {
console.log("连接关闭!");
setTimeout(() => {
that.reconnect()
}, 3000);
};
webSocket.onerror = function () {
console.log("连接异常!");
};
}
},
// 重连
reconnect() {
console.log('重新连接')
this.contactSocket()
},