websocket 封装js 心跳,断网重连,收发信息,页面直接调用

websocket.js    :新建一个文件

1.websocket.js  文件   

export default class WebSocketManager {
	constructor(url = null, receiveMessageCallback = null) {
		this.socket = null // WebSocket 对象
		this.pingTimeout = null // 心跳计时器
        this.reconnectTimeout = null //重联计时器
		this.reconnectTimeoutClock = 5000 // 重连间隔,单位:毫秒
		this.maxReconnectAttempts = 10 // 最大重连尝试次数
		this.reconnectAttempts = 0; // 当前重连尝试次数
		this.url = url // WebSocket 连接地址
		this.receiveMessageCallback = receiveMessageCallback // 接收消息回调函数
	}
	/**
		 * 初始化
		 */
	async start() {
		if (this.url) {
			// 连接WebSocket
			this.connectWebSocket()
		} else {
			console.error('WebSocketerros: 请传入连接地址')
		}
	}
	/**
		 * 创建WebSocket连接
		 */
	connectWebSocket() {
		// 创建 WebSocket 对象
		this.socket = new WebSocket(this.url)

		// 处理连接打开事件
		this.socket.addEventListener('open', event => {
			// 心跳机制
			this.startHeartbeat()
		})

		// 处理接收到消息事件
		this.socket.addEventListener('message', event => {
			this.receiveMessage(event)
		})

		// 处理连接关闭事件
		this.socket.addEventListener('close', event => {
			// 清除定时器
			clearTimeout(this.pingTimeout)
			clearTimeout(this.reconnectTimeout)
			// 尝试重连
			if (this.reconnectAttempts < this.maxReconnectAttempts) {
				this.reconnectAttempts++
				this.reconnectTimeout = setTimeout(() => {
					this.connectWebSocket()
				}, this.reconnectTimeoutClock)
			} else {
				// 重置重连次数
				this.reconnectAttempts = 0
				console.error('已达到最大重新连接尝试次数。无法重新连接。')
			}
		})

		// 处理 WebSocket 错误事件
		this.socket.addEventListener('error', event => {
			console.error('WebSocketManager error:', event)
		})

        
	}
	/**
		 * 启动心跳机制
		 */
	startHeartbeat() {
		this.pingTimeout = setInterval(() => {
			// 发送心跳消息
			this.sendOrderMessage('heartCheck')
		}, 10000) // 每隔 10 秒发送一次心跳
	}

	/**
	 * 发送消息
	 * @param {String} message 消息内容
	 */
	sendOrderMessage(message) {
		if (this.socket.readyState === WebSocket.OPEN) {
			this.socket.send(message);
		} else {
			console.error('WebSocketManager error: WebSocket连接未打开,无法发送消息。')
		}
	}
	/**
		 * 接收到消息
		 */
	receiveMessage(event) {
		// 根据业务自行处理
		console.log('receiveMessage:', event.data)
		// 传入回调函数自行处理
		this.receiveMessageCallback && this.receiveMessageCallback(event.data)
	}
	/**
		 * 关闭连接
		 */
	closeWebSocket() {
		this.socket.close()
		// 清除定时器 重置重连次数
		clearTimeout(this.pingTimeout)
		clearTimeout(this.reconnectTimeout)
		this.reconnectAttempts = 0
	}
}

2.页面引用:

说明,如果是在vue项目里面,直接写在script里面,复制就行,不能写在 vue页面的export里面。

  <script >
        import WebSocketManager  from './websocket.js';
        const  messageBack = (msg) => {
            console.log('接收消息回调',msg);
            //可做页面消息处理
        }
        const socket = new WebSocketManager('wss://xxxx',messageBack);
        socket.start()


    </script>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值