vue.js中实现websocket通信
前后端websocket通信具体实践:
代码片
.
methods: {
// socket 通信开始
init: function() {
if (typeof WebSocket === "undefined") {
console.log("您的浏览器不支持socket");
// alert("您的浏览器不支持socket");
} else {
console.log("支持");
// 实例化socket
let id =this.userID;
this.socket = new WebSocket("ws://" + window.location.host + "/项目名/websocket/"+ id);
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket错误信息
this.socket.onerror = this.error;
// 监听socket消息
this.socket.onmessage = this.getMessage;
}
},
open: function() {
console.log("socket连接成功");
},
error: function() {
console.log("连接错误");
},
getMessage: function(msg) {
// 处理业务逻辑
// let _data = JSON.parse(msg.data);
},
send: function() {
// 向服务器端发送消息
this.socket.send("收到了吗????");
console.log("send");
},
close: function() {
this.socketState = "close";
console.log("socket已经关闭");
}
}