vue的webSocke双工通信,实时性刷新数据
data() {
return {
path: "ws://192.168.2.121:9080/api/websocket",//后台生成的通信域名地址
socket: "",
};
},
methods: {
init() {
if (typeof WebSocket === "undefined") {
alert("您的浏览器不支持socket");
} else {
// 实例化socket
// this.socket = new WebSocket(this.path,[token]) //传token
this.socket = new WebSocket(this.path);
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket错误信息
this.socket.onerror = this.error;
// 监听socket消息
this.socket.onmessage = this.getMessage;
}
},
open() {
console.log("socket连接成功");
},
error() {
console.log("连接错误");
},
getMessage(msg) {
console.log(JSON.parse(msg.data), "6666");
},
send() {
this.socket.send(123);
},
close() {
console.log("socket已经关闭");
}
}
mounted() {
// 初始化
this.init();
},
连接成功时-