Reconnection of Client when server reboots in WebSocket

后端 未结 9 2211
青春惊慌失措
青春惊慌失措 2020-12-02 05:03

I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.

I run the server, and

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 05:46

    The client side close event for WebSocket has a wasClean property, which was useful to me. Seems like it is set to true in cases where the client computer goes into sleep mode etc. or when the server is unexpectedly stopped etc. It is set to false if you manually close the socket, in which case you don't want to open the socket automatically again. Below code from an Angular 7 project. I have this code in a service, so it is usable from any component.

        notifySocketClose(event) { 
    
            if (!event.wasClean) { 
                setTimeout(() => {
                    this.setupSocket()
                }, 1000);       
            }
        }
    
        setupSocket() { // my function to handle opening of socket, event binding etc.
        .....
        .....
    
                this.websocketConnection = this.websocketConnection ? this.websocketConnection : new WebSocket(socketUrl);
                this.websocketConnection.onclose = this.notifySocketClose.bind(this);   
            } 
        }
        .....
        .....
    
    

提交回复
热议问题