In this chapter, we'll be working extensively with WebSockets. To fully understand the workings of the chat application that we're going to build, let's first have a look at how WebSockets work.
The WebSockets protocol is specified in RFC 6455 and uses HTTP as the underlying transport protocol. In contrast to the traditional request/reply paradigm, in which the client sends a request to the server, who then replies with a response message, WebSocket connections can be kept open for a long time, and both server and client can send and receive messages (or data frames) on the WebSocket.
WebSocket connections are always initiated by the client (so, typically, a user's browser). The following listing shows an example request that a browser might send to a server supporting WebSockets:
GET /chat HTTP/1.1 Host: localhost Upgrade: websocketConnection: upgrade Origin: http://localhost Sec-WebSocket-Key: de7PkO6qMKuGvUA3OQNYiw== Sec-WebSocket-Protocol: chat Sec-WebSocket...