created() {
//初始化websocket
this.initWebSocket();
},
destroyed() {
this.websock.close() //离开路由之后断开websocket连接
},
methods: {
initWebSocket() {
//初始化websocket
let wsurl = "ws://225.225.225.225:8080/orderPage/ws"
this.websock = new WebSocket(wsurl);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
//连接建立之后执行send方法发送数据
console.log("连接建立之后执行send方法发送数据");
this.websocketsend('userName');
},
websocketonerror() {
console.log('连接建立失败重连')
//连接建立失败重连
if (this.websock.readyState === 3) {
this.initWebSocket();
}
},
websocketonmessage(e) {
console.log("数据接收", e);
},
websocketsend(Data) {
console.log("数据发送", Data);
//数据发送
this.websock.send(Data);
},
websocketclose(e) {
//关闭
console.log("断开连接", e);
//断开链接重连
if (this.websock.readyState === 3) {
this.initWebSocket();
}
}
},
websocket建立连接
最新推荐文章于 2024-05-23 14:09:49 发布