Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconnection of Client when server reboots in WebSocket

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 the client is also connected. I can chat as well. Now when I restart the server (by killing it and starting it again), the client gets the disconnected information, but automatically doesn't reconnect with server when I send the message.

How to achieve this? Like when I get the dis-connected information, should I check it and send it to JavaScript to refresh the page or reconnect?

like image 441
siddhusingh Avatar asked Sep 23 '10 16:09

siddhusingh


People also ask

Does WebSocket automatically reconnect?

clear-ws handles reconnects automatically (if you provide not null reconnect.

How do I reconnect to WebSocket after closing connection?

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object's onclose method to a function that reconnects after a set timeout. const connect = () => { const ws = new WebSocket("ws://localhost:8080"); ws.

What causes WebSocket disconnect?

By default, if a ping has not been received in 60 seconds, and the connection has been otherwise inactive, the platform will close the WebSocket. This timeout is configurable in the WS Communication Subsystem configuration, Idle Connection Timeout (sec) parameter.

Can server close WebSocket connection?

The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.


1 Answers

When the server reboots, the Web Socket connection is closed, so the JavaScript onclose event is triggered. Here's an example that tries to reconnect every five seconds.

function start(websocketServerLocation){     ws = new WebSocket(websocketServerLocation);     ws.onmessage = function(evt) { alert('message received'); };     ws.onclose = function(){         // Try to reconnect in 5 seconds         setTimeout(function(){start(websocketServerLocation)}, 5000);     }; } 
like image 192
Andrew Avatar answered Oct 04 '22 12:10

Andrew