vue3.0 连接websocket
step(){
const state :any = reactive({
websocketUrl: WebSocket,
isReconnect: false,
isConnect: false,
})
}
const initWebscoket =()=>{
state.websocketUrl = new WebSocket("后端接口位置") // string
state.websocketUrl.open =()=>{
console.log('连接成功')
state.isConnect = true
}
state.websocketUrl.onmessage =(e)=>{
console.log('接收成功')
webmessage(Json.parse(e.data))
}
state.websocketUrl.onerror =()=>{
consoloe.log('连接失败')
state.isConnect = false
// 重新连接
reConnectwebsocket()
}
state.websocketUrl.onclose =()=>{
console.log('连接关闭')
state.isConnect = false
// 重新连接
reConnectwebsocket()
}
}
// 重新连接
const reConnectwebsocket = () =>{
if(state.isReconnect) return
state.isReconnect = true
console.log('正在重新连接')
//时间间隔,避免请求过多
state.reconnectTimeout = setTimeout(()=>{
initWebscoket()
state.isReconnect = false
}, 5000)
}
// 接收到的消息处理
const webmessage =(val)=>{
// 消息的处理
}
// 发送消息
const messageSend = ()=>{
// 首先判断是否连接
if(state.isConnect) {
let curent = {
// 消息以及需要传递给后端的东西
}
// 只能发送string 所以做Json.stringify() 处理 ,同样获取到的数据要做Json.pare()处理
state.websocket.send(Json.stringify(current))
} else {
console.log(‘正在连接中....’)
return false
}
}
// 清除 websocket
const closeWebsocket = ()=>{
state.isConnect = false
state.isReconnet = false
state.websocketUrl.onclose = null
state.websocketUrl.onerror = null
state.websocketUrl?.close()
state.websocketUrl = WebSocket
// 清除定时器
clearTimeout(state.reconnectTimeout)
console.log('断开连接,清除websocket')
}
websocket(vue3.0)
最新推荐文章于 2024-07-29 22:01:22 发布