封装一个websocket类

463 阅读1分钟

一、想法

在vue项目中如果不想在另外的`.vue`文件中定义websocket组件,可以封装一个专属`websocket`类,在其他文件中
引入并实例化这个类来使用,这样可以保证每个实例化对象都是相对独立的,并切灵活性更高。

二、实现

1、创建websocket类

  • 在一个单独的文件中创建websocket类
    export default class WebSocketClient {
        constructor(url) {
            this.url = url
            this.websocket = null
            this.heartbeatInterval = null
            this.heartbeatTimeout = null
        }
        
        connect() {
            this.createWebSocket()
            this.startHeartbeat()
        }
        
        createWebSocket() {
            this.websocket = new WebSocket(this.url)
            this.websocket.onopen = this.websocketOnOpen.bind(this)
            this.websocket.onmessage = this.websocketOnMessage.bind(this)
            this.websocket.onclose = this.websocketOnClose.bind(this)
            this.websocket.onerror = this.websocketOnError.bind(this)
        }
        
        websocketOnOpen() {
            console.log("WebSocket连接成功")
        }
        
        websocketOnMessage(event) {
            console.log("收到消息:", event.data)
        }
        
        websocketOnClose() {
            console.log("WebSocket连接关闭")
            this.reconnectWebSocket()
        }
        
        websocketOnError() {
            console.log("WebSocket连接错误")
            this.recommectWebSocket()
        }
        
        reconnectWebSocket() {
            if(this.websocket) {
                this.websocket.close()
                this.websocket = null
            }
            setTimeout( () => {
                this.createWebSocket()
            },3000)
        }
        
        startHeartbeat() {
            this.heartbeatInterval = setInterval( () => {
                if(this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                    this.websocket.send("heartbeat")
                    this.heartbeatTimeout = setTimeout( () => {
                        console.log("WebSocket连接断开,开始重连")
                        this.reconnectWebSocket()
                    }, 5000)
                }
            }, 10000)
        }
        
        stopHeartbeat() {
            clearInterval(this.heartbeatInterval)
            clearTimeout(this.heartbeatTimeout)
        }
        
        close() {
            this.stopHeartbeat()
            if(this.websocket) {
                this.websocket.close()
                this.websocket = null
            }
        }
    }

2、在其他文件中引入WebSocket类

  • 在需要使用WebSocket的文件中,引入该WebSocket类
    import WebSocketClient from "./WebSocketClient"
    
    const websocket = new WebSocketClient("ws://loacalhost:3360")
    websocket.connect()

3、使用websocket类

  • 在实例化WebSocket类之后,可以调用connect方法来连接WebSocket服务器
    websocket.connect()
  • 在不需要使用WebSocket时,可以调用close方法来关闭WebSocket连接
    websocket.close()