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建立连接
最新推荐文章于 2026-06-30 21:38:24 发布
该代码段展示了在Vue.js应用中如何创建、管理和关闭WebSocket连接。在`created()`钩子中初始化WebSocket,`destroyed()`中关闭连接。当连接打开时发送数据,错误发生时尝试重连,接收到消息和关闭事件时有相应的回调处理。
1920

被折叠的 条评论
为什么被折叠?



