Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 993
Qwer Sense Avatar asked Jun 15 '18 13:06

Qwer Sense


People also ask

Does WebSocket use keepalive?

Keepalive in websockets To avoid these problems, websockets runs a keepalive and heartbeat mechanism based on WebSocket Ping and Pong frames, which are designed for this purpose.

How does WebSocket ping pong work?

Pings and Pongs: The Heartbeat of WebSocketsAt any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.

When WebSocket connection is closed?

The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.

Can WebSockets close servers?

Either the client or the server sends a Close frame (WebSockets borrow a lot of TCP terminology, so you exchange data in “frames”), and the other side sends back its own Close frame in response, and then both parties can close their connections.


1 Answers

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.

like image 70
ouni Avatar answered Sep 20 '22 18:09

ouni