benyu
benyu

Reputation: 11

Socket.io 0.7 can not call broadcast.send?

in socket.io 0.6, i have following example code:

var io = require('/usr/lib/node_modules/socket.io');
var server = http.createServer(function(req,res){
      var path = url.parse(req.url).pathname;
      switch( path ){
           ....
           //core codes
           socket.broadcast(data);
      }
}).listen(8080);

// ... ...

var socket = io.listen(server);

and everything going ok.

But now i have renew the socket.io to 0.7 and have changed the socket.broadcast to socket.sockets.broadcast.send(data) ;

Got an exception : can not call send of 'undefined'?

Who can tell me how can i send data to everybody without listening on a certain event?

Maybe here is a way:

clients = new Array();
socket.on('connection',function(socket){ clients.push(socket);}
// ...
for(s in clients) s.send(data);
// ...

does it really needed to do like this way?

Thanks!

Upvotes: 1

Views: 2330

Answers (3)

3rdEden
3rdEden

Reputation: 4416

In socket.io 0.7 you do:

io.sockets.send() // broadcasts to all connected users
io.sockets.json.send() // broadcasts JSON to all connected users
io.sockets.emit('eventname') // broadcasts and emit

or to namespaces

io.of('/namespace').send('msg'); // broadcast to all connect users in /namespace

Upvotes: 2

Daniel Baulig
Daniel Baulig

Reputation: 10989

Use

sioServer.sockets.on('connection', function (client) {
    client.broadcast.send('Hello, Everybody else!');
});

to broadcast to every other connected client (that is except the broadcasting client himself) and use

sioServer.sockets.on('connection', function (client) {
    sioServer.sockets.send('Hello, Everybody!');
});

to broadcast to everybody (including client himself).

Upvotes: 0

Philipp Kyeck
Philipp Kyeck

Reputation: 18820

you can just do

var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
  socket.broadcast.emit('user connected');
});

Upvotes: 0

Related Questions