Note: Our friends at The Hybrid Group wrote this great post on how to use WebSockets for us. Thanks guys!
In this post, we'll be covering an introduction to WebSockets, and implementing a basic WebSockets chat app using EM-WebSocket.
WebSockets is one of the cooler new features in the HTML5 spec, and allows clients and servers to communicate without using AJAX requests, or HTTP long-polling(Comet).
What are WebSockets?
WebSockets are, according to the specification:
an API that enables Web pages to use the WebSocket protocol (defined by the IETF) for two-way communication with a remote host.
Essentially, WebSockets can replace existing HTTP long-polling solutions. WebSockets allow for a single, long-held TCP connection to be established between the client and server. This allows for full-duplex, bi-directional messaging between both sides with very little overhead (and, as a result, very little latency).
The WebSocket specification defines two new URI scemes,ws:and_wss:_, for unencrypted and encrypted WebSocket connections respectively.
The current WebSockets spec is supported by the following browsers:
- Chrome 16
- Internet Explorer 10
- Opera 12
- Safari 6
Run it with:
And now we have a good start for our chat application. Next, we'll get the server side of things set up.
First, let's get the server set up to run within EventMachine, and handle a WebSocket connection. This is made really simple by
em-websocket, and we don't even need to handle the headers for the WebSocket handshake:
This will take care of the WebSocket handshake with clients, and take care of the chat backend. Now, let's set up the client!
This will set up our clients to be able to interact with the WebSocket server we just set up. The server will take any messages the client sends, and re-broadcast it to all clients.
First, let's write basic functions to display messages on the page:
Now, let's set up a connection with our WebSocket server, and set it up to connect as soon as the browser's ready:
Now we can set up the logic to send messages to the server whenever the user presses the return key (keycode 13). This will send the message to the server, and let the user know that the message has been sent:
And, last but not least, let's let our users disconnect from the server if they want to:
And this wraps up our client side. It will now open a WebSocket connection to our server, send/receive messages, and disconnect if the user wants to.
Now we have a working chat service. To start it, we run the same command as before:
Now you can browse to
http://localhost:3000/, and see the chat system in action. Try opening it in multiple browsers to test it out! If you'd like to check out the full source code, you can find it on GitHub.