Omar Bahir
Omar Bahir

Reputation: 1257

Broadcasting in socket.io?

How to broadcast a message among all the connected clients in socket.io?

I am using mrniko/netty-cosket.io server with with java (play/eclipse) on server side and socket.io.js 0.9 on client side. Both client & server working fine (i.e. sending and receiving messages). To keep the records of the connected clients , I am using hashMaps and to send a message to all connected users I am iterating the hashmap and sending messages one by one. just wanna know is there any better way to send messages to all connected clients at once?

Any help will be highly appreciated.

Upvotes: 0

Views: 1538

Answers (2)

Nikita Koksharov
Nikita Koksharov

Reputation: 10783

Here is an example in case of mrniko/netty-socket.io usage:

Configuration config = new Configuration();
    config.setHostname("localhost");
    config.setPort(9092);

SocketIOServer server = new SocketIOServer(config);

BroadcastOperations bo = server.getBroadcastOperations();
// every method will broadcast messages to all server clients
bo.sendJsonObject(...)

server.start();
...

Upvotes: 2

Kurt Pattyn
Kurt Pattyn

Reputation: 2788

you can use the following code:

//broadcasts to all clients connected
io.sockets.emit('function', {foo:bar});

//broadcasts to all clients connected, except the sender
io.sockets.on('connection', function (socket) {
    socket.on('message', function(data) {
        socket.broadcast.emit('function', {foo:bar}); 
    }
}

Upvotes: 1

Related Questions