JS webSocket 封装

本文介绍如何在JavaScript中封装WebSocket类,并实现数据的持久化,确保跨文件可以使用相同的实例化对象。通过示例代码展示WebSocket的使用方法和持久化策略。
摘要由CSDN通过智能技术生成

webSocket 类封装

webSocket.js 文件代码如下:

// webSocket类

class Socket {
	// 接收消息参数
	message = null;
	constructor(options) {
		const { url, heartTime, reconnectTime } = options;
		const classSelf = this;

		this.reconnectTime = reconnectTime || 5000; // 重连时间
		this.lockReconnect = false;//避免重复连接
		this.ws = null; //WebSocket的引用
		this.wsUrl = url; //这个要与后端提供的相同
		//心跳检测
		this.heartCheck = {
			timeout: heartTime || 15000,//毫秒
			timeoutObj: null,
			serverTimeoutObj: null,
			reset: function () {
				clearTimeout(this.timeoutObj);
				clearTimeout(this.serverTimeoutObj);
				return this;
			},
			start: function () {
				const self = this;
				this.timeoutObj = setTimeout(function () {
					//这里发送一个心跳,后端收到后,返回一个心跳消息, 【发送格式与后端沟通】
					//onmessage拿到返回的心跳就说明连接正常
					classSelf.ws.send(JSON.stringify({ type: "HeartBeat"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值