Hello, we are 29 Steps. We build software using Ruby.

Socket.io is a real time communication framework which allows you to publish real time information to your web app and I have been using a lot of it lately in one of my current projects running on nodejs.

One of the criteria I needed was to allow for a ‘channel’ type behavior whereby based on a specific item selection the socket is subscribed to a channel and then unsubscribed when another link is clicked such as a ‘close’ option. Although socket.io does not have channels built in, we can mimic the same behaviour using the ‘room’ functionality, built in from version 7.7 onwards.

A ‘room’ is a logical organization of sockets which should belong to a specific category or group e.g. a socket for grabbing the latest tweets based on a particular trend. ┬áTo add the current socket to a specific room, just use the join syntax.

socket.join('topic');

To remove the socket from the ‘room’ just apply the leave fuction, specifying the name of the room.

socket.leave('topic');

To access the particular socket at a later point, just access the list of sockets based on the main socket.io object specifying the room/channel name:

var socket = io.sockets.in('topic');

The gist belows highlight some of the methods mentioned above in use in a production application.

<script src=”https://gist.github.com/1243781.js?file=node_socketio_example.js”></script>

Accessing the specific ‘room’ or channel on the client side

On the client side, you need to specify each client connection as a new object in order for the server to recognise it as a new client connection from the frontend:

var client = io.connect("myapp.com", { port:80, 'force new connection': true });

The syntax above replaces the older new io.Socket constructor call.

Then simply send a message to the server as per the example above to register the socket on the server side to this particular client connection:

client.send('my-topic')

The above will invoke the on 'message' block on the server side, registering the client to the specified room/channel

For a visual explanation of how it works please check out Tweet Streamer, a realtime twitter stream based on the Twitter Streaming API using nodejs and socket.io