<template>
<div>
<button @click="send">发消息</button>
</div>
</template>
export default {
data () {
return {
path:"ws://192.168.0.200:8005/qrpage/id=1/refreshtime=5",
socket:""
}
},
mounted () {
window.onbeforeunload = function () {
this.close()
}
// 初始化
this.init()
},
methods: {
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket(this.path)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
this.socket.onclose = this.close
}
},
open: function () {
console.log("socket连接成功");
let actions = {"test":"12345"};
this.send(JSON.stringify(actions));
},
error: function () {
console.log("连接错误")
this.init()
},
getMessage: function (msg) {
const redata = JSON.parse(msg.data);
// 接收数据
console.log(redata);
},
send: function (Data) {
this.socket.send(Data)
},
close: function () {
console.log("socket已经关闭")
}
},
destroyed () {
// 销毁监听
this.close()
}
}
网友评论