How to implement free of charge ping pong in cloudflare Durable Object Websocket

I want to implement ping pong in my DO websocket so it's possible to know when the client is offline, since the websocket alone does not tells that.

But I want to avoid extra charge for each ping/pong.

Cloudflare says pings are not charged. Consider the following:

https://developers.cloudflare.com/durable-objects/platform/pricing/
2 A request is needed to create a WebSocket connection. There is no charge for outgoing WebSocket messages, nor for incoming WebSocket protocol pings ↗.


Here is the protocol reference link:
https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2
5.5.2.  Ping

   The Ping frame contains an opcode of 0x9.

   A Ping frame MAY include "Application data".

   Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
   response, unless it already received a Close frame.  It SHOULD
   respond with Pong frame as soon as is practical.  Pong frames are
   discussed in Section 5.5.3.

   An endpoint MAY send a Ping frame any time after the connection is
   established and before the connection is closed.

   NOTE: A Ping frame may serve either as a keepalive or as a means to
   verify that the remote endpoint is still responsive.

5.5.3.  Pong

   The Pong frame contains an opcode of 0xA.

   Section 5.5.2 details requirements that apply to both Ping and Pong
   frames.

   A Pong frame sent in response to a Ping frame must have identical
   "Application data" as found in the message body of the Ping frame
   being replied to.

   If an endpoint receives a Ping frame and has not yet sent Pong
   frame(s) in response to previous Ping frame(s), the endpoint MAY
   elect to send a Pong frame for only the most recently processed Ping
   frame.


How can I implement that opcodes in both DO and client to ensure Cloudflare will understand the messages as the ping protocol?
My client is native browser websocket new Webocket()
Was this page helpful?