Webscoket
主要的api
const ws=new WebSocket('ws://192.168.0.200:8005') //创建ws实例
ws.onopen=()=>{} //连接ws
ws.onerror=()=>{} //接收错误消息
ws.onmessage=()=>{} //接收后端发送的数据
ws.onclose=()=>{} //关闭ws
使用
xxx.vue
<template>
<div>
<button @click="send">发消息</button>
</div>
</template>
<script>
export default {
data () {
return {
path:"ws://192.168.0.200:8005/qrCodePage/ID=1/refreshTime=5",
socket:""
}
},
mounted () {
// 初始化
this.init()
},
methods: {
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
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: function () {
console.log("socket连接成功")
},
error: function () {
console.log("连接错误")
},
getMessage: function (msg) {
console.log(msg.data)
},
send: function () {
this.socket.send(params)
},
close: function () {
console.log("socket已经关闭")
}
},
destroyed () {
// 销毁监听
this.socket.onclose = this.close
}
}
</script>
<style>
</style>
常见的问题
问题描述:在长时间不发送消息的时候,会自动断开。
解决思路:心跳保持连接:实现心跳检测的思路是: 每隔固定的时间,发送一个数据到服务器,服务器接收之后,返回一个数据给客户端。如果客户端onmessage事件能监听到返回的数据,则表示连接未断开。否则,表示连接断开,需要客户端去重新发送请求进行连接。
start() { // 发送心跳
clearInterval(this.timeoutObj)
this.timeoutObj = setInterval(() => {
let date = new Date()
this.socket.send(`发送心跳给后端${date}`)
}, 2 * 60 * 1000)
}
如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/