Reconnection of Client when server reboots in WebSocket

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

    function wsConnection(url){
        var ws = new WebSocket(url);
        var s = (l)=>console.log(l);
    	ws.onopen = m=>s(" CONNECTED")
        ws.onmessage = m=>s(" RECEIVED: "+JSON.parse(m.data))
        ws.onerror = e=>s(" ERROR")
        ws.onclose = e=>{
            s(" CONNECTION CLOSED");
            setTimeout((function() {
                var ws2 = new WebSocket(ws.url);
    			ws2.onopen=ws.onopen;
                ws2.onmessage = ws.onmessage;
                ws2.onclose = ws.onclose;
                ws2.onerror = ws.onerror;
                ws = ws2
            }
            ).bind(this), 5000)
        }
        var f = m=>ws.send(JSON.stringify(m)) || "Sent: "+m;
        f.ping = ()=>ws.send(JSON.stringify("ping"));
        f.close = ()=>ws.close();
        return f
    }
    
    c=new wsConnection('wss://echo.websocket.org');
    setTimeout(()=>c("Hello world...orld...orld..orld...d"),5000);
    setTimeout(()=>c.close(),10000);
    setTimeout(()=>c("I am still alive!"),20000);
    This code will create a websocket which will 
    reconnect automatically after 5 seconds from disconnection.
    
    An automatic disconnection is simulated after 10 seconds.

提交回复
热议问题