
1.**publicMethods.js**
//websocket
export function openSocket(uuid) {
let env = process.env.VUE_APP_WEBSOCKET;
let url = `ws://${env}/tdmsWs/webSocket/${uuid}`;
let socket = new WebSocket(url);
// let data;
//打开事件
socket.onopen = () => {
console.log("websocket已打开");
};
// //获得消息事件
// socket.onmessage = (msg) => {
// console.log(msg.data, "websocket123456")
// };
//关闭事件 (websocket可在服务端配置连接超时时间)
socket.onclose = function (e) {
console.log("websocket已关闭");
//打印错误信息
console.log(
"websocket 断开: " + e.code + " " + e.reason + " " + e.wasClean
);
console.log(e);
};
//发生了错误事件
socket.onerror = function () {
console.log("websocket发生了错误");
//连接建立失败重连
openSocket(uuid);
};
return socket;
}
2. **main.js 挂载公共方法**
import {openSocket} from "./PublicMethod";
Vue.prototype.$openSocket = openSocket;
3.**子组件应用**
this.$openSocket(this.uuid).onmessage = (msg) => {
console.log("收到服务器内容", msg.data);
};
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)