HTML and CSS Reference
Figure 13-17. The Agent page with multiple sessions
In this relatively brief introduction to WebSockets you created a simple chat system that allows an agent to chat
with multiple clients simultaneously. While the server implementation was pretty involved, the client side was
fairly simple. After creating the WebSocket object, specifying the location of the WebSocket server, you just wire
up event handlers to be notified when the connection is established, when a message is received, and when the
connection has been closed.
In this demo, you created a standalone application, but in many cases you'll simply add the chat capability
to your existing web application. For example, you might ask the user if they want assistance with the page they
are viewing and if they do, this simple code will allow them to chat right from that page.
The server side requires a bit of protocol handling. First, the server receives handshaking messages using
http . The request key is obtained and used to generate the response key. The entire response is then sent back to
the client. The actual messages are sent using the ws protocol, which includes a frame header. Messages from the
client are masked, which require logic in the server to unmask it. Messages from the server are not masked.
The demo application provides a chat capability. This is only one possible use of WebSockets. They can also
be used any time the server needs to initiate communication with the client. Keep in mind, however, that the
client must initiate the connection with the server.