Skip to content
erichua23 edited this page Aug 23, 2012 · 12 revisions

Messaging

Sending messages is one of the most important aspects of working with Socket.IO.

Message flags

Message flags allow Socket.IO to process messages or events differently, these flags allows you to configure how the messages should be send or emitted to the client. This allows you to write flexible and agile messaging system on top Socket.IO.

Using message flags is not required but they can simplify the development process of your application by doing all the hard work for you. The following flags are available on the server side:

.broadcast

Sends the message or event to every connected user in the current namespace, except to your self.

var io = require('socket.io').listen(80);
io.of('/namespace').on('connection', function (socket) {
  socket.broadcast.send('Hi, a new user connected');
});

.json

Sends the supplied message through JSON.stringify before it sends it to the user. If you are sending objects, arrays etc without the JSON flag we will perform a toString operation on it.

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
  socket.json.send({foo:'bar'});
});

.volatile

This is basically fire and forget functionally, these messages are not buffered internally for when a client is unable to receive messages for example if the client has network issues or if the client uses a polling transport and is in the middle of a request/response cycle.

So if it doesn't matter if your client misses a couple of messages or events you might want to send these as volatile messages.

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
  setInterval(function () {
   socket.volatile.send("it's: " + new Date);
  }, 500);
});

The message flags are chain-able and can be used together with other flags. And this can be done in any order that makes sense to you.

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
  socket.broadcast.volatile.json.send({'foo':'bar'});
  socket.volatile.broadcast.emit('ping', 'pong');
  socket.json.broadcast.send([{foo:'bar'}, {'ping': 12}]);
});