<template>
<div class="test">
</div>
</template>
<script>
export default {
data() {
return {
websock: null,
}
},
methods: {
// 初始化weosocket
initWebSocket(){
if(typeof(WebSocket) === "undefined"){
console.log("您的浏览器不支持WebSocket")
}else{
const wsurl = "ws://192.168.0.29:10052/vehicle-location";
// 实例化 WebSocket
this.websock = new WebSocket(wsurl);
// 监听 WebSocket 连接
this.websock.onopen = this.websocketonopen;
// 监听 WebSocket 错误信息
this.websock.onerror = this.websocketonerror;
// 监听 WebSocket 消息
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
}
},
// 连接建立之后执行send方法发送数据
websocketonopen(){
console.log("socket连接成功")
let actions = {"hxw":"是我男神"};
this.websocketsend(JSON.stringify(actions));
},
// 连接建立失败重连
websocketonerror(){
console.log("连接错误");
this.initWebSocket();
},
// 数据接收
websocketonmessage(e){
const resdata = e.data
// console.log(e);
// console.log(resdata);
},
// 数据发送
websocketsend(Data){
this.websock.send(Data);
},
// 关闭
websocketclose(e){
console.log('WebSocket 断开连接',e);
},
},
beforeMount() {
this.initWebSocket();
},
destroyed() {
//离开路由之后断开 websocket 连接
this.websock.close();
},
}
</script>
webcoket推送链接
最新推荐文章于 2024-09-13 23:32:49 发布
该段代码展示了在Vue.js中如何初始化并使用WebSocket进行通信。当WebSocket连接打开时,向服务器发送数据;如果连接出现错误,则尝试重新连接;接收到服务器消息时进行处理,并在组件销毁时关闭WebSocket连接。
摘要由CSDN通过智能技术生成