Vue websocket封装
created() {// 连接websocketthis.initWebSocket();},methods: {// 初始化weosocketinitWebSocket() {const path = 'ws://192.168.107.10:8083/ws/zhangsan';this.webSocket = new WebSocket(path);this.webSocket.onmess
·
created() {
// 连接websocket
this.initWebSocket();
},
methods: {
// 初始化weosocket
initWebSocket() {
const path = 'ws://192.168.107.10:8083/ws/zhangsan';
this.webSocket = new WebSocket(path);
this.webSocket.onmessage = this.webSocketMsg;
this.webSocket.onopen = this.openWebsocket;
this.webSocket.onerror = this.webSocketError;
this.webSocket.onclose = this.closeWebSocket;
},
// 开启websocket
openWebsocket() {
// 发送心跳,可以字符串,也可以是Object
let heartMsg = {
messagetype: 7,
data: {
operation_type: 1,
operation_options: 0,
operation_data: null
},
err: ""
}
this.sendWebSocket(heartMsg);
},
webSocketError() {
//连接建立失败重连
this.initWebSocket();
},
webSocketMsg(e) {
//数据接收
console.log(e.data);
},
sendWebSocket(data) {
//数据发送
this.webSocket.send(JSON.stringify(data));
},
closeWebSocket(e) {
//关闭
this.webSocket.close();
}
}
更多推荐
已为社区贡献14条内容
所有评论(0)