How to implement Ping/Pong request for webSocket connection alive in javascript?

Qwer Sense picture Qwer Sense · Jun 15, 2018 · Viewed 43.4k times · Source

I use websocket in javascript. But the connection close after one minute.

I am wondering somethings:

1- Is not Websocket naturaly providing with Ping/Pong messages not to close the connection? I think it have to. Otherwise what is the difference between websocket and TCP connection?

2- If I have to send the ping/pong messages, how is the ping message sent? What am I need to do? Is WebSocket object provide a ping method? Or should I call a method as websocket.send("ping") ? I am use naturaly WebSocket object in javascipt.

3- Should the server respond to Ping requests with Pong? Should this be implemented separately on the server side?

Note:Sorry for my english.

Answer

ouni picture ouni · Jun 16, 2018

At this point in time, heartbeats are normally implemented on the server side: there's not much you can do from the client end.

However, if the server keeps killing your socket connection, and you have no control over it, it is possible for the client to send arbitrary data to the websocket on an interval:

let socket = null;

function connect_socket() {
  socket = new WebSocket(ws_url);
  socket.on("close", connect_socket); // <- rise from your grave!
  heartbeat();
}

function heartbeat() {
  if (!socket) return;
  if (socket.readyState !== 1) return;
  socket.send("heartbeat");
  setTimeout(heartbeat, 500);
}

connect_socket();

I strongly recommend trying to sort out what's happening on the server end, rather than trying to work around it on the client.