记录一下websocket在vue(2)和uniapp中如何封装和使用,代码可直接复制使用

1.在vue中使用

   在工具类文件夹下新建WebSocketHelper.js文件

class WebSocketHelper {
    constructor(url, heartbeatInterval = 300000) {
        this.url = url; // WebSocket 服务器地址
        this.heartbeatInterval = heartbeatInterval; // 心跳间隔(毫秒)
        this.ws = null; // WebSocket 实例
        this.heartbeatTimer = null; // 心跳定时器
        this.onMessageCallback = null; // 消息回调
        this.isAlive = true; // 连接存活状态
    }

    // 连接 WebSocket
    connect() {
        this.ws = new WebSocket(this.url); // 创建 WebSocket 实例

        // WebSocket 连接打开时的回调
        this.ws.onopen = () => {
            console.log('WebSocket 连接成功');
            this.startHeartbeat(); // 开始心跳
            setTimeout(() => {
                this.send('ping'); // 发送 ping 消息
            }, 100);
        };

        // WebSocket 收到消息时的回调
        this.ws.onmessage = (event) => {
            // console.log('收到消息:', event.data);
            if (this.onMessageCallback) {
                this.onMessageCallback(event.data); // 调用消息回调
            }
            if (event.data === 'pong') {
                this.isAlive = true; // 更新连接状态
            }
        };

        // WebSocket 关闭时的回调
        this.ws.onclose = () => {
            console.log('WebSocket 已关闭');
            this.stopHeartbeat(); // 停止心跳
        };

        // WebSocket 错误时的回调
        this.ws.onerror = (error) => {
            console.error('WebSocket 发生错误:', error);
            this.stopHeartbeat(); // 停止心跳
        };
    }

    // 发送消息
    send(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) { // 检查连接是否已打开
            this.ws.send(message);
            console.log('消息发送成功:', message);
        } else {
            console.warn('WebSocket 未连接');
        }
    }

    // 启动心跳机制
    startHeartbeat() {
        this.heartbeatTimer = setInterval(() => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.isAlive = false; // 重置为 false
                this.send('ping'); // 发送 ping 消息

                // 设置超时,如果未收到 pong 响应,则认为连接已断开
                setTimeout(() => {
                    if (!this.isAlive) {
                        console.warn('未收到 pong 响应,连接可能已断开');
                        this.close(); // 关闭连接
                    }
                }, this.heartbeatInterval);
            }
        }, this.heartbeatInterval);
    }

    // 停止心跳
    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    }

    // 关闭 WebSocket 连接
    close() {
        if (this.ws) {
            this.ws.close();
            console.log('WebSocket 连接已关闭');
        }
    }

    // 设置消息回调
    setOnMessageCallback(callback) {
        this.onMessageCallback = callback;
    }
}

export default WebSocketHelper;

在需要使用websocket文件中引入该方法

import WebSocketHelper from '@/utils/WebSocketHelper.js';
export default{
    name: 'test',
    data() {
        return {
            timer: null, // 定时器
            time: '',  //显示实时时间
            wsHelper: null,
            serverUrl: 'ws://', //你的websocket地址
        };
    },
    created(){
       this.wsHelper = new WebSocketHelper(this.serverUrl); // 创建 WebSocketHelper 实例
       this.wsHelper.setOnMessageCallback(this.handleMessage); // 设置消息回调
       this.wsHelper.connect(); // 连接 WebSocket
       this.timer = setInterval(() => {
            // 获取时间的方法
            this.time = this.$getTime();
        }, 1000);
    },
    methods:{
      handleMessage(message) {
        // message即为接受到的数据,在该方法中进行数据的处理和赋值
      },
    },
    beforeDestroy() {
        this.wsHelper.close(); // 页面卸载时关闭 WebSocket 连接
        clearInterval(this.timer);
    },
}

2.在uniapp中使用

在工具类文件夹下新建WebSocketHelper.js文件

// WebSocketHelper.js
class WebSocketHelper {
	constructor(url, heartbeatInterval = 300000) {
		this.url = url; // WebSocket 服务器地址
		this.heartbeatInterval = heartbeatInterval; // 心跳间隔(毫秒)
		this.ws = null; // WebSocket 实例
		this.heartbeatTimer = null; // 心跳定时器
		this.onMessageCallback = null; // 消息回调
		this.isAlive = true; // 连接存活状态
	}

	// 连接 WebSocket
	connect() {
		this.ws = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log('WebSocket 连接成功');
				this.startHeartbeat(); // 开始心跳
				setTimeout(()=>{
					this.send('ping');
				},100)
			},
			fail: (error) => {
				console.error('WebSocket 连接失败', error);
			}
		});

		// 监听 WebSocket 事件
		this.ws.onOpen(() => {
			console.log('WebSocket 已打开');
		});

		this.ws.onMessage((res) => {
			// console.log('收到消息:', res.data);
			if (this.onMessageCallback) {
				this.onMessageCallback(res.data); // 调用消息回调
			}
			if (res.data === 'pong') {
				this.isAlive = true; // 更新连接状态
			}
		});

		this.ws.onClose(() => {
			console.log('WebSocket 已关闭');
			this.stopHeartbeat(); // 停止心跳
		});

		this.ws.onError((error) => {
			console.error('WebSocket 发生错误:', error);
			this.stopHeartbeat(); // 停止心跳
		});
	}

	// 发送消息
	send(message) {
		if (this.ws && this.ws.readyState === 1) { // 1 表示连接已打开
			this.ws.send({
				data: message,
				success: () => {
					console.log('消息发送成功:', message);
				},
				fail: (error) => {
					console.error('消息发送失败:', error);
				}
			});
		} else {
			console.warn('WebSocket 未连接');
		}
	}

	// 启动心跳机制
	startHeartbeat() {
		this.heartbeatTimer = setInterval(() => {
			if (this.ws && this.ws.readyState === 1) {
				this.isAlive = false; // 重置为 false
				this.send('ping'); // 发送 ping 消息

				// 设置超时,如果未收到 pong 响应,则认为连接已断开
				setTimeout(() => {
					if (!this.isAlive) {
						console.warn('未收到 pong 响应,连接可能已断开');
						this.close(); // 关闭连接
					}
				}, this.heartbeatInterval);
			}
		}, this.heartbeatInterval);
	}

	// 停止心跳
	stopHeartbeat() {
		if (this.heartbeatTimer) {
			clearInterval(this.heartbeatTimer);
			this.heartbeatTimer = null;
		}
	}

	// 关闭 WebSocket 连接
	close() {
		if (this.ws) {
			this.ws.close();
			console.log('WebSocket 连接已关闭');
		}
	}

	// 设置消息回调
	setOnMessageCallback(callback) {
		this.onMessageCallback = callback;
	}
}

export default WebSocketHelper;

在需要使用的文件中引用该方法

import WebSocketHelper from '@/utils/WebSocketHelper.js';
export default{
   data(){
    return {
	  wsHelper: null,
	  serverUrl: 'ws://', //请求地址
    }
  },
   onLoad(){
     this.wsHelper = new WebSocketHelper(this.serverUrl); // 创建 WebSocketHelper 实例
	 this.wsHelper.setOnMessageCallback(this.handleMessage); // 设置消息回调
	 this.wsHelper.connect(); // 连接 WebSocket
   },
   onUnload() {
	 this.wsHelper.close(); // 页面卸载时关闭 WebSocket 连接
   },
   methods:{
     handleMessage(message){
      // message即为接受到的数据,在该方法中操作数据
     }
   }
}

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐