Using socket.io to broadcast to one, some, or all sockets


In prior articles we used node.js and socket.io to create a page that listed the number of connected clients. We used socket.io to broadcast a message to all connected sockets. But what if you only wanted to broadcast a message to the client that just connected, or some subset of all of the connected clients you have? Socket.io has many ways to do that!

You’re probably already familiar with how to broadcast to all connected sockets:

io.sockets.emit(‘message’, {foo:bar});
1
io.sockets.emit(‘message’, {foo:bar});

Sending a message to a single client is similar. Instead of emitting using io.sockets we instead just use socket:

socket.emit(‘message’, {foo:bar});
1
socket.emit(‘message’, {foo:bar});

Or we can broadcast to all clients except for one with:

socket.broadcast.emit(‘message’, {foo:bar});
1
socket.broadcast.emit(‘message’, {foo:bar});

Rooms

You can also partition clients into “rooms” and sending messages to clients within a room.

Have your client join a room:

socket.join(‘room’)
1
socket.join(‘room’)

And then broadcast a message to the clients in that room:

io.sockets.in(‘room’).emit(‘message’, {foo:bar});
1
io.sockets.in(‘room’).emit(‘message’, {foo:bar});

You can learn more about socket.io’s concept of rooms here.

Copy from http://www.scottblaine.com/2012/using-socket-io-broadcast-one-some-sockets/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s