HTML and CSS Reference
Deploying TLS requires cryptographic digital certificates that are used to identify
WebSocket servers. In production environments, these certificates must be signed by
a certificate authority (CA) that is known and trusted by web browsers. If you use an
untrusted certificate, users will see security errors when accessing your server, which is
how TLS prevents man-in-the-middle attacks from hijacking connections as they open.
During development, you can sign your own certificates and configure your browser to
trust those certificates and ignore the security warnings.
WebSocket Pings and Pongs
Connections can unexpectedly close for many reasons beyond your control. Any web
application should be coded to gracefully deal with intermittent connectivity and recover
appropriately. There are, however, reasons connections close that can and should be
avoided. One common cause of connectivity loss that is avoidable is inactivity at the TCP
level, which in turn affects WebSocket connections.
■ Because Websocket connections are layered on top of TCP connections,
connection issues that occur at the TCP level affect Websocket connections.
With a full-duplex connection between your client and WebSocket server, there
may be times when there is no data flowing over the connection. At that point, a network
intermediary may terminate the connection. Specifically, network components that are
not aware of “always on” connections sometimes close down inactive TCP, and therefore
WebSocket, connections. For example, proxy servers and home routers sometimes
terminate what they perceive as idle connections. The WebSocket Protocol supports
pings and pongs both to perform health checks on the connection and to keep the
Using WebSocket pings and pongs keeps the connection open and ready for data
flow. Pings and pongs can originate from either side of an open WebSocket connection.
The WebSocket Protocol supports client-initiated and server-initiated pings and pongs.
The browser or server can send pings, pongs, or both at appropriate intervals to keep
connections active. Note that we've said browser, and not WebSocket client: as we
mentioned in Chapter 2, the WebSocket API does not currently support client-initiated
pings and pongs. While the browser may send pings and pongs according to its own keep-
alive and health-check policies, most pings and pongs are going to be server-initiated;
the WebSocket client can then respond to pings with a pong. Alternatively, the browser
or server can send pongs without receiving a ping, which gives you flexibility in keeping
your connections alive. The exact intervals you use depend on the audience for your
application and the normal rate of data flowing over your application's WebSocket
connections. Conservatively, sending a pong every thirty seconds ought to keep most
connections alive, but sending pongs less frequently saves bandwidth and server