Socket.io 0.7不能调用broadcast.send?
在socket.io 0.6中,我有以下示例代码:
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);
一切顺利。
但现在我已经将socket.io更新到0.7,并将socket.broadcast更改为socket.sockets.broadcast.send(data);
有一个例外:不能调用发送'undefined'?
谁能告诉我怎样才能把数据发送给每个人而不用听某个事件呢?
也许这是一个方法:
clients = new Array(); socket.on('connection',function(socket){ clients.push(socket);} // ... for(s in clients) s.send(data); // ...
它真的需要这样做吗?
谢谢!
在socket.io 0.7中你可以:
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
或命名空间
io.of('/namespace').send('msg'); // broadcast to all connect users in /namespace
你可以做
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.broadcast.emit('user connected'); });
使用
sioServer.sockets.on('connection', function (client) { client.broadcast.send('Hello, Everybody else!'); });
向所有其他连接的客户端(即广播client
本人除外)进行广播和使用
sioServer.sockets.on('connection', function (client) { sioServer.sockets.send('Hello, Everybody!'); });
向所有人(包括client
自己)进行广播。