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.

###Browser Support

The current WebSockets spec is supported by the following browsers:

Chrome 16

Internet Explorer 10

Opera 12

Safari 6

###Getting Started

To get started on building our Em-WebSocket chat app, let’s build a very basic Sinatra app running within EventMachine. We’re going to need to use thin, since it supports EventMachine:

And now we have a good start for our chat application. Next, we’ll get the server side of things set up.

###WebSockets Server

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:

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:

$("#disconnect").click(function() {
socket.close()
});

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.

###Conclusion

Now we have a working chat service. To start it, we run the same command as before:

bundle exec ruby app.rb

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.

For some further reading on WebSockets, you may wish to consult the spec. Additionally, there’s some good info on the MDN, but that site isn’t 100% complete yet.