Reconnection of Client when server reboots in WebSocket

后端 未结 9 2167
青春惊慌失措
青春惊慌失措 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:48

    Finally, I make ws auto reconnect in vue+ts, similar as following:

    private async mounted() {
        // Connect to WebSocket
        const sn = "sb1234567890";
        const host =
            window.location.protocol == "https:"
                ? "wss://www.xxx.net"
                : process.env.DEV_TYPE === "fullstack"
                ? "ws://10.0.0.14:8528"
                : "ws://www.xxx.net:8528";
        const wsUri = host + "/feed-home/" + sn;
        await this.startWs(wsUri, sn);
        // !!!Deprecated: failed to reconnect
        // let ws = new WebSocket();
        // console.log(ws);
        // ws.onopen = async function(event) {
        //     console.log(event, "openEvent");
        //     clearInterval(that.timer);
        // };
        // ws.onclose = async function(event) {
        //     console.log(event, "close");
        //     that.timer = setInterval(() => {
        //         console.log("Heart Beat");
        //         ws.send("HeartBeat");
        //         // ws = new WebSocket("ws://10.0.0.14:8528/feed-home/" + sn);
        //         console.log(ws);
        //     }, 60000);
        // };
        // ws.onmessage = async function(event) {
        //     console.log(event, "ws");
        //     alert("get it!");
        //     await alert("please update!");
        //     await that.getHome(sn);
        // };
    }
    private wsReconnected: boolean = false; // check whether WebSocket is reconnected
    private async startWs(uri: string, sn: string) {
        let that = this;
        let ws = new WebSocket(uri);
        ws.onopen = async () => {
            if (that.wsReconnected) {
                await that.getHome(sn); // Refresh api data after reconnected
            }
            ws.send("Current client version: " + window.version);
        };
        ws.onmessage = async evt => {
            await that.getHome(sn);
            that.$message({
                type: "success",
                message: evt.data,
                showClose: true,
                center: true,
                duration: 20 * 1000
            });
        };
        ws.onclose = async () => {
            that.wsReconnected = true;
            await that.startWs(uri, sn);
            const sleep = (seconds: number) => {
                return new Promise(resolve =>
                    setTimeout(resolve, seconds * 1000)
                );
            };
            await sleep(10); // Try to reconnect in 10 seconds
            // !!!Deprecated: Use timer will cause multiply ws connections
            // if (!that.wsTimer) {
            //     // Try to reconnect in 10 seconds
            //     that.wsTimer = setInterval(async () => {
            //         console.log("reconnecting websocket...");
            //         await that.startWs(uri, sn);
            //     }, 10 * 1000);
            // }
        };
    }
    
    0 讨论(0)
  • 2020-12-02 05:53

    ReconnectingWebSocket

    GitHub hosts a small JavaScript library that decorates the WebSocket API to provide a WebSocket connection that will automatically reconnect if the connection is dropped.

    Minified library with gzip compression is less than 600 bytes.

    The official repository is available here:

    https://github.com/joewalnes/reconnecting-websocket

    Server flood

    If a high number of clients are connected to the server when it reboots. It may be worthwhile to manage the reconnect timings of the clients by using an Exponential Backoff algorithm.

    The algorithm works like this:

    1. For k attempts, generate a random interval of time between 0 and 2^k - 1,
    2. If you are able to reconnect, reset k to 1,
    3. If reconnection fails, k increases by 1 and the process restarts at step 1,
    4. To truncate the max interval, when a certain number of attempts k has been reached, k stops increasing after each attempt.

    Référence:

    http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app

    ReconnectingWebSocket does not handle reconnections by using this algorithm.

    0 讨论(0)
  • 2020-12-02 05:53

    Below are the codes i have used in my project which working 100%.

    1. Put all the websocket code inside the init function.
    2. Inside the onclose callback call the init again.
    3. Finally call the init function inside the document ready function.

    var name = sessionStorage.getItem('name');

    wsUri =  "ws://localhost:8080";   
    var websocket;
    $(function() {  
        init();  
        $("#chat_text_box").on("keypress", function(e) {         
            if (e.keyCode == 13) {   //For Enter Button    
                e.preventDefault();
                var mymessage = $('#chat_text_box').val();               
                if(mymessage){
                    var msg = {  type: 'chat_text',  data : {  name:name,  msg:mymessage }  };                
                    console.log(msg);
                    websocket.send(JSON.stringify(msg));
                    $('#chat_text_box').val('');
                }               
                return false;                       
            }        
        });      
    });     
    function init() { 
        websocket = new WebSocket(wsUri);      
        websocket.onopen = function(ev) { /*connection is open */    } 
        websocket.onmessage = function(ev) {        
            var data = JSON.parse(ev.data); //PHP sends Json data        
            var type = data.type;//alert(JSON.stringify(data));
            switch(type) {
                case "chat_text":
                    var text = "<div><span class='user'>"+data.data.sender_name+" : </span><span class='msg'>"+data.data.msg+"</span></div>";
                    $('#chat-messages').append(text);
                    break;            
                default:
                    break;
    
            }        
    
        };     
        websocket.onerror   = function(ev){}; 
        websocket.onclose = function(ev) {   init();   };  
    }
    
    0 讨论(0)
提交回复
热议问题