// webSocket.js let Socket = '' let setIntervalWesocketPush = null let socketUrl = ""; /** * 建立websocket连接 * @param {string} url ws地址 */ export const createSocket = () => { let userId = JSON.parse(localStorage.getItem('userInfo')).id; let w = location.protocol.indexOf("https") > -1 ? "wss" : "ws"; let h = location.host; socketUrl = `${w}://${h}/notification/${userId}`; Socket && Socket.close() if (!Socket) { console.log('建立websocket连接') Socket = new WebSocket(socketUrl) Socket.onopen = onopenWS Socket.onmessage = onmessageWS Socket.onerror = onerrorWS Socket.onclose = oncloseWS } else { console.log('websocket已连接') } } /**打开WS之后发送心跳 */ const onopenWS = () => { sendPing() } /**连接失败重连 */ const onerrorWS = () => { Socket.close() clearInterval(setIntervalWesocketPush) console.log('连接失败重连中') if (Socket.readyState !== 3) { Socket = null createSocket(socketUrl) } } /**WS数据接收统一处理 */ const onmessageWS = e => { window.dispatchEvent(new CustomEvent('onmessageWS', { detail: { data: e.data } })) } /** * 发送数据但连接未建立时进行处理等待重发 * @param {any} message 需要发送的数据 */ const connecting = message => { setTimeout(() => { if (Socket.readyState === 0) { connecting(message) } else { Socket.send(JSON.stringify(message)) } }, 1000) } /** * 发送数据 * @param {any} message 需要发送的数据 */ export const sendWSPush = message => { if (Socket !== null && Socket.readyState === 3) { Socket.close() createSocket(socketUrl) } else if (Socket.readyState === 1) { Socket.send(JSON.stringify(message)) } else if (Socket.readyState === 0) { connecting(message) } } /**断开重连 */ const oncloseWS = () => { clearInterval(setIntervalWesocketPush) console.log('websocket已断开....正在尝试重连') if (Socket.readyState !== 2) { Socket = null createSocket(socketUrl) } } /**发送心跳 * @param {number} time 心跳间隔毫秒 默认20000 * @param {string} ping 心跳名称 默认字符串ping */ export const sendPing = (time = 1000 * 20, ping = 'ping') => { clearInterval(setIntervalWesocketPush) Socket.send(ping) setIntervalWesocketPush = setInterval(() => { Socket.send(ping) }, time) }
调用
import { createSocket } from '@/utils/webSocket';
createSocket();
在需要数据的页面
// methods
getsocketData (e) { // 创建接收消息函数 let data = e && e.detail.data if (data && data != 'ping' && data.indexOf("消息格式不正确") < 0) { this.unReaderNum = parseInt(data); // 接收数据的操作 let par = { num: 1, size: 5, msgType: '', status: '0', } postMessagePage(par).then(r => { this.msgList = r.data; }) } }
//mounted
window.addEventListener('onmessageWS', this.getsocketData);
分类:
Vue 杂记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2020-02-28 Uncaught TypeError: Cannot read property 'disabled' of null