本文主要是介绍vue3之 websoket发送消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.封装websoket
var ws = null; //建立的连接
var lockReconnect = false;//是否真正建立连接
var timeout = 6 * 1000 * 5;//30秒一次心跳
var timeoutObj = null;//心跳心跳倒计时
var serverTimeoutObj = null;//心跳倒计时
var timeoutnum = null;//断开 重连倒计时
var global_callback = null; //监听服务端消息
var openId = localStorage.getItem('openId')
// uri: 长链接地址<br>// jwt: 前后端连接凭证, 按需添加<br>// callback: 服务端消息回调函数
export function createWebscoket(uri, callback) {global_callback = callbackws = new WebSocket(uri)ws.onopen = () => {lockReconnect = truews.send(JSON.stringify({ "userId": openId, "toUserId": openId, "msgType": 0 }));//开启连接心跳start()}ws.onmessage = onMessagews.onerror = onError// ws.onclose = onClosews.onsend = onSend
}//发送消息
export function onSend(message) {console.log(`发送消息: ${message}`)console.log(ws.readyState)if (ws.readyState != 1) {reset()// reconnect()// ws.send(message)} else {ws.send(message)}}//接受服务端消息
// export function onMessage(res) {
// let msgData = res ? res.data : {}
// console.log(msgData)
// if (typeof msgData != 'object') {
// // var data = msgData.replace(/\ufeff/g, "");
// var message = JSON.parse(msgData);
// if (message.code == 0) {
// return
// } else {
// //重置心跳
// reset()
// }
// //服务端消息回掉
// // ws.onmessage()
// global_callback(message)
// // console.log( ws.onmessage())
// }
// }
export function onMessage(res){let msgData = res ? res.data : {}if (typeof msgData != 'object' && msgData != 'Connect success') {var data = msgData.replace(/\ufeff/g, "");var message = JSON.parse(data)//服务端消息回掉global_callback(message)//重置心跳reset()}}//连接失败
export function onError() {console.log('连接失败')ws.close()ws = nulllockReconnect = false
}//连接关闭
export function onClose() {console.log('连接关闭')
}
//断开关闭
export function closeWs() {if (lockReconnect) {ws.close()ws = nulllockReconnect = false}
}// 发送心跳
export function start() {timeoutObj && clearTimeout(timeoutObj);serverTimeoutObj && clearTimeout(serverTimeoutObj);timeoutObj = setTimeout(function () {//这里发送一个心跳,后端收到后,返回一个心跳消息if (ws.readyState == 1) { //如果连接正常ws.send(JSON.stringify({ "userId": openId, "toUserId": openId, "msgType": 0 }));// ws.send(data)} else { //否则重连reconnect()}serverTimeoutObj = setTimeout(function () {//超时关闭ws.close();}, timeout);}, timeout + 3000)
}
//重置心跳
export function reset() {var that = this;//清除时间clearTimeout(timeoutObj);//清除时间clearTimeout(serverTimeoutObj);start(); //重启心跳
}//重新连接
export function reconnect() {if (lockReconnect) {return;};lockReconnect = true;//没连接上会一直重连,设置延迟避免请求过多timeoutnum && clearTimeout(timeoutnum);timeoutnum = setTimeout(function () {createWebscoket();//新连接lockReconnect = false;}, 5000);
}
2.页面调用
import { createWebscoket, onSend, closeWs, start } from '@/utils/socket.js'
onMounted(() => {let host = process.env.VUE_APP_WS_HOST //ws地址createWebscoket(host + token.value, messagesCallBack)})//新消息监听
const messagesCallBack = (msg) => {console.log(msg)
}//断开socket
const closeWsTxt = () => {closeWs()
}//发送socket消息到服务器
const sendMessagext = (data) => {onSend(JSON.stringify(data))
}
这篇关于vue3之 websoket发送消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!