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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With