HTML and CSS Reference
Building Instant Messaging
and Chat over WebSocket
Chat is a great example of an Internet application that has become more difficult to
build in an HTTP-only world. Chat and instant messaging applications are inherently
asynchronous: either party can send a message at will without requiring a specific request
or response. These applications are excellent use cases for WebSocket as they benefit
hugely from reduced latency. When chatting with your friends and colleagues, you want
as little delay as possible in order to have natural conversations. After all, if there were lots
of lag, it would hardly be instant messaging.
Instant messaging is a perfect fit for WebSocket; chat applications are common
demos and examples of this technology. Most common examples use simplistic custom
messages instead of a standard protocol. In this chapter, we delve much deeper than
these basic demos, using a mature protocol to tap into a wealth of different server
implementations, powerful features, and proven scalability and extensibility.
First, we explore layering protocols with WebSocket and some of the key choices
you need to make before building an application that uses a higher-level protocol over
WebSocket. In this example, we use XMPP, which stands for eXtensible Messaging and
Presence Protocol, and is a standard that is widely used in instant messaging applications.
We take advantage of this protocol for communication by using it on top of a WebSocket
transport layer. In our example, we step through connecting a web application to the
Jabber Instant Messaging (IM) network using XMPP over WebSocket, including adding
the ability to indicate user's status and online presence.
In Chapter 3, we discussed simple demonstrations of the WebSocket Protocol that involve
sending and receiving messages directly on the WebSocket layer. Our remote control
console example demonstrated that it is possible to use WebSocket to build simple
applications involving bidirectional communication. Imagine extending simple demos