欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Vue使用socket实现实时通信

Vue使用socket实现实时通信

2024/10/26 2:35:14 来源:https://blog.csdn.net/ct5211314/article/details/140323278  浏览:    关键词:Vue使用socket实现实时通信

一、新建socket文件

class SocketService {constructor() {this.socket = null;this.reconnectTimer = null;this.messageCallback = null;this.connectionParams = null;this.path=null}init() {this.clearReconnectTimer(); // 尝试重新连接之前先清除重连定时器if (typeof WebSocket === "undefined") {throw new Error("您的浏览器不支持WebSocket");}this.socket = new WebSocket(this.path);this.socket.addEventListener("open", this.open.bind(this));this.socket.addEventListener("error", this.error.bind(this));this.socket.addEventListener("close", this.close.bind(this));this.socket.addEventListener("message", this.getMessage.bind(this));}open() {console.log('%c [ WebSocket已连接 ]', 'font-size:16px; background:#7fce50; color:white;')this.clearReconnectTimer();}close(event) {console.log('%c [ WebSocket已关闭并断开连接 ]', 'font-size:16px; background:red; color:white;')this.destroyWebsocket();}error(event) {console.log('%c [ WebSocket已断开连接 ]', 'font-size:16px; background:red; color:white;')this.startReconnectTimer();}getMessage(event) {if (event.data === "连接成功") {return;}const message = event.data;if (this.messageCallback) {this.messageCallback(message);}}startReconnectTimer() {if (!this.reconnectTimer) {this.reconnectTimer = setInterval(() => {console.log('%c [ WebSocket已断开 尝试重新连接... ]', 'font-size:16px; background:red; color:white;')if (this.connectionParams) {this.init();}}, 3000); // 重连间隔为 3 秒}}clearReconnectTimer() {if (this.reconnectTimer) {clearInterval(this.reconnectTimer);this.reconnectTimer = null;this.clearReconnectTimer();}}destroyWebsocket() {if (this.socket) {this.socket.close();this.socket = null;this.clearReconnectTimer();this.messageCallback = null; // 或者清除 messageCallback 的引用}}
}const socketService = new SocketService();
export default socketService;

二、引入并调用

//引入
import socketService from "./socket.js";
//开启
initSocketService() {// const id = '';const path = `${Monitor_Alarm}${this.tenantId}/${this.userInfo.id}`;// const path =// 	"ws://aes.aes-iot.com:8301/sys-alarm/ws/dashboard/admin/d35fd488525686145aca387b0158c234";// let url = .replace(/^https?:\/\//g, "");// const path = `ws://${url}/sys-alarm/ws/dashboard/802/10000`;// const type = "device";// 初始化 WebSocket 连接 传递类型 设备idsocketService.path = path;socketService.init();socketService.messageCallback = this.handleMessage;},
//接收消息后的处理
handleMessage(message) {}
//关闭
this.closeWebsocket();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com