vue使用websoket
作者:互联网
参考链接:https://www.cnblogs.com/qisi007/p/10213886.html
export default { name: "realdetail", components: {}, data() { return { wsuri: null, websock: null } }; }, created() { this.wsuri = "ws://127.0.0.1:8210";//监听地址 this.initWebSocket(); }, destroyed() { this.websock.close() //离开路由之后断开websocket连接 }, methods: {initWebSocket() { //初始化weosocket this.websock = new WebSocket(this.wsuri); this.websock.onmessage = this.websocketonmessage; this.websock.onopen = this.websocketonopen; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose; }, websocketonopen() { //连接建立之后执行send方法发送数据 let message = { type: "login", data: {"mn":this.deviceInfo.mn} }; console.log(message); this.websocketsend(JSON.stringify(message)); }, websocketonerror() { //连接建立失败重连 this.initWebSocket(); }, websocketonmessage(e) { //数据接收 const redata = JSON.parse(e.data); console.log(redata) this.handlerData(redata); this.$forceUpdate(); // 强制刷新一下数据 }, websocketsend(Data) { //数据发送 this.websock.send(Data); }, websocketclose(e) { //关闭 console.log('断开连接', e); }, handlerData(data) { if (data.type) { switch (data.type) { case "realData": this.updateRealData(data.data); this.deviceInfo.onlineStatus=1; break; case "online": this.deviceInfo.onlineStatus=1; break; case "offline": this.deviceInfo.onlineStatus=0; break; } } }, //更新实时数据 updateRealData(data){ this.realData=this.handleRealData(data); } }
在线测试websocket:http://coolaf.com/tool/chattest
标签:websoket,vue,console,deviceInfo,break,websock,使用,message,data 来源: https://www.cnblogs.com/webttt/p/15292425.html