171

I keep reading about ping/pong messages in websockets to keep the connection alive, but I'm not sure what they are. Is it a distinct frame type? (I don't see any methods on a javascript WebSocket object in chrome related to ping-pong). Or is it just a design pattern (e.g. I literally send "ping" or any other string to the server and have it respond). Is ping-pong at all related to continuation frames?

The reason I ask is I'm using a python framework that runs behind Mongrel2, so I'm wondering if there's a way to send Mongrel2 a specific ping/pong message that would tell it to keep the connection alive without my python app needing to worry about it. Analogous to a having a separate HTTP method for it, I guess. And I imagine a dedicated ping/pong message frame could be simpler (less load on server and network) than the string "ping", though that probably wouldn't matter too much.

EDIT: I just looked at RFC 6455 and it looks like Ping and Pong are definitely control frame types with their own opcodes. So how do I send a Ping frame from javascript in Chrome?

4
  • Just ping from the server. Everyone knows about the networking issue on non-standard ports, so they're starting to ping at regular short intervals. I guess you could ping a poorly written server, but it might not be too smart to do anything sensitive with them.
    – user1382306
    Feb 10, 2014 at 13:48
  • 1
    @user1382306 ping from server first will use mobile device battery use very fast. Ping from client can save device battery.
    – bronze man
    Jul 9, 2018 at 2:52
  • 2
    @user1382306 Not quite everyone! What is the networking issue on non-standard ports?
    – HappyDog
    Aug 16, 2018 at 22:23

4 Answers 4

157

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

2
10

Update: Although the answer is old, it's in google's top results. At any point after the handshake, either the client or the server can choose to send a ping to the other party

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.

21
  • 106
    Where have you read that ping is only from server to client ? The RFC says "An endpoint MAY send a Ping frame any time after the connection is established and before the connection is closed."
    – xryl669
    Apr 15, 2014 at 10:28
  • 10
    If you want the client to automatically detect a disconnected state (when no RST/FIN packets have been received, but the network has been disconnected), then you need to have the client initiate ping packets as well.
    – pschwamb
    May 30, 2014 at 4:08
  • 21
    TCP does not notify of disconnects when RST/FIN packets were not received. TCP only detects dropped connections when a sender attempts to send on a disconnected connection. Pings are used as heartbeats in many applications and it's a valid use. A dead connection will simply remain dead forever until the client tries to send. Therefore, with WebSockets on the browser, a custom ping (or heartbeat) message must be used to detect client disconnect on the client side. The server may be trying to ping, and detecting the client disconnect, but the client is not informed. Client pings are also fine.
    – DDS
    Jan 1, 2015 at 8:13
  • 22
    In RFC 6455, The WebSocket Protocol, it explicitly states: "NOTE: A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive."
    – DDS
    Jan 1, 2015 at 8:17
  • 7
    It's possible that the server-only ping was a recommended practice when user-agents were frequently refreshed. But now many websites are designed as SPAs. In this environment it might be quite essential for the client application to regularly ping the server in order to ensure the connection has not been lost. May 19, 2016 at 10:08
7

a possible solution in js

In case of the WebSocket server initiative disconnects the ws link after a few minutes there were no messages be sent between the server and client.

  1. the client end initiative sends a custom ping message, to keep alive by using the keepAlive function

  2. the server end will ignore the custom ping message and responds to a custom pong message

let timerId = 0; 

function keepAlive(timeout = 20000) { 
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}

function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

3
  • 2
    This code sends empty frames, not ping or pong frames. Nov 28, 2020 at 0:47
  • 1
    @RememberMonica Please read my description first, I know what's going on.
    – xgqfrms
    Nov 29, 2020 at 12:07
  • This gave me light to a keep-alive function which in my case is notifying the server to renew reading deadline value on the websocket connection (btw I'm in golang server in my case). Though I had to make it more meaningful by simulating it to send a pong string. Thank you! from Tanzania. Dec 16, 2020 at 8:23
3

No.

I attempted to implement a ping. There doesn't seem to be any way I can force a browser WebSocket client to set any opcode other than 0x1 (string) and 0x2 (binary).

const socket = new WebSocket(url);
ping() {
    if (socket?.readyState !== WebSocket.OPEN) {
      return;
    }
    const buffer = new ArrayBuffer(7);
    const dataView = new DataView(buffer);
    dataView.setInt8(0, 0x89);
    dataView.setInt8(1, 0x00);
    dataView.setInt8(2, 0x48);
    dataView.setInt8(3, 0x65);
    dataView.setInt8(4, 0x6c);
    dataView.setInt8(5, 0x6c);
    dataView.setInt8(6, 0x6f);
    socket.send(buffer);
  }
socket.addEventListener('open', ping);

This code should send a final (0x8) ping frame (opcode 0x09) with body "hello", but the browser sends a final frame in binary (0x82) that has body "�hello" where � is the 0x89 data.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.