Using Socket.io: WebSockets with Fallbacks

If you want to create a real-time game without the hassles of worrying about browser compatibility and fallbacks, a number of libraries are available that can help, but one of the most popular and simplest to use is Socket.io, available at http://socket.io.

Socket.io is a Node library that abstracts WebSockets and multiple supported fallbacks on both the client and the server side. It also provides the capability to transparently send JSON data over sockets and adds support for any number of custom events. Socket.io also integrates nicely into Express, which means you can use a single app to serve your HTTP methods, your WebSockets, and your static files. Add in support for heartbeats, timeouts, and disconnection support, and you see why using a library over straight WebSockets makes your life easier.

To become familiar with Socket.io before building a game using the library, you’ll build a simple multiuser scribble application that enables people to scribble over each other’s drawings in real time.

Creating the Scribble Server

On the server side, Socket.io works by listening for connection events. These events trigger a callback with a socket object. You can then attach additional listeners for both standard events, such as disconnect and custom named events.

To send data you can call socket.emit with a name for the event and any data that needs to be passed along. You can send events to all sockets except the socket itself by calling ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.