在vue中一次链接webSocket,多次通讯使用;
1、首先在app.vue 中建立连接;直接写一个function 调用
localSocket() {
// webSocket
let that = this;
if ('WebSocket' in window) {
console.log('浏览器支持webSocket');
// WebSocketURL 自己定义的全局ip地址如:ws://47.****.120.123/appSocketServer 此地址由后台提供;
that.ws = new WebSocket(WebSocketURL);
that.webSocketTool.setWs(that.ws);
// that.ws.onopen = that.ws.onopen();
that.ws.onclose = function() {
// 关闭 websocket
console.log("连接已关闭...");
setTimeout(() => {
that.localSocket();
}, 2000);
};
} else {
// 浏览器不支持 WebSocket
console.log("您的浏览器不支持 WebSocket!");
}
}
2、在需要通讯的子页面中接收发送信息
// 发送和接收消息
webSocketHanddleMsg(msg) {
let that = this;
if (that.webSocketTool.ws && that.webSocketTool.ws.readyState == 1) {
console.log(“发送信息”, msg);
that.webSocketTool.ws.send(msg);
}
that.webSocketTool.ws.onmessage = function(res) {
console.log(“收到服务器内容”, res);
// 根据接收到的后台数据格式自行选择是否需要处理;
that.PayWebScoketJSON = JSON.parse(res.data);
// 异步存储 结合vuex将信息存储全局
that.$store.commit(‘setIsPayWebScoketData’, res.data);
// 接受当前大厅是否已经到达交易时间 type类型,交易时间结束的大厅id
console.log(“that.hallInfo.id”);
console.log(that.hallInfo.id);
// 业务代码
if(that.PayWebScoketJSON.type == 6 && that.PayWebScoketJSON.id == that.hallInfo.id) {
console.log(‘交易时间结束#######################’);
that.hallPigLists =[];
that.tipMsg = ‘交易大厅关闭。’
}else{
console.log(‘交易时间进行中&&&&&&&&&&#######################’);
}
};
},