HTML5 is loaded with a lot of features that will make the lives of developers much easier and the experience for end users more pleasant as well. Lets take a look one of the new features: WebSockets. We’ll make the magic happen with Ruby’s EventMachine gem.
If you’re in a browser that supports WebSockets (Chrome, Safari, Firefox trunk), go ahead and type a bit. Your keystrokes will be captured, and broadcasted to any other users on the page. If this page is lonely, you can open a second browser window to test it out.
Using EventMachine for WebSockets is simple with the
em-websockets gem. Start an EventMachine.run
block and
EventMachine::WebSocket.start
will do the rest. It provides a socket object
that resembles the javascript WebSocket spec with callbacks for onopen, onmessage,
and onclose.
In the example, connected sockets are added to an array and broadcasted to when onmessage is triggered.
The client side script listens for keypresses and sends them to the websocket. On receiving a message, which is just a single letter in this case, the corresponding letter will be lit up.
With it all put together, WebSockets makes for a simple way to connect users together through the browser without plugins, polling, or other ugly frameworks.
20 Aug 2010