I saw a project on freelancer and that wanted to see phonegap and socket.io in action. I put on my thinking cap and started exploring. Socket.io is a beautifully brewed concept where sockets are used for transport.
Namespaces
There are namespaces, which you can create and the client will connect to that.
Each namespace emits a connection event that receives each Socket instance as a parameter.
Rooms
Also, sockets can be put in channels. When an socket is initialized, it is part of a room which is equal to its socket id.
And then simply use to or in (they are the same) when broadcasting or emitting:
To leave a channel you call leave in the same fashion as join.
Default room
Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id.
This makes it easy to broadcast messages to other sockets:
Disconnection
Upon disconnection, sockets leave all the channels they were part of automatically, and no specially teardown is needed on your part.
Knowing this, I leaped into code.
The client side code is as below:
And the server side code is:
To start serving through node, run the commend (preferably in screen, so that it keeps running):