Namespacing in socket.io when sending to a particular socket
When i namespace my app, i run into a problem i want to send data to a particular socket, here'开发者_C百科s the abbreviated version of the code I'm using:
var io = require('socket.io').listen(config.web.port);
var chat = io.of('space').on('connection', function (socket) {
// This works:
// Input: xhr-polling received data packet 5::/space:{"name":"test"}
// Output: xhr-polling writing 5::/space:{"name":"test","args":[{"msg":"test"}]}
socket.on('test', function(){
socket.emit('test',{msg: "test"});
});
// This fails:
// Input: xhr-polling received data packet 5::/space:{"name":"test2"}
// Output: xhr-polling writing 5:::{"name":"test2","args":[{"msg":"test2"}]}
socket.on('test2',function(){
io.sockets.socket(socket.id).emit('test2',{msg: "test2"});
});
}
As you can see, the second one lacks the namespace part from the output. In the real app I'm picking the socket id from a client manager so I'm using socket.id in this piece of code instead of client.getSocketId(), but the idea is the same as I'm just echoing to the origin client here.
How do i make the second method to use the correct namespace when outputting to the client?
After checking out the source for SocketNamespace
, it appears the syntax is io.of('space').socket(id).emit(...
.
[Edit per Fuu's comment]
To find this, I checked the Socket.IO GitHub repository and looked for a file that would have to do with namespaces--namespace.js
seemed to fit the bill. The file wasn't very long, so I scanned it looking for methods on SocketNamespace
's prototype that looked like it might do what we wanted.
Since you call io.sockets.socket
to find a socket on the global namespace, SocketNamespace.prototype.socket
stuck out to me as being promising. Furthermore, it takes a parameter called sid
, and the body of the method appears to be fetching a socket from a hash of sockets by this ID. A Socket
is what we want (it holds the emit
method), so my presumption was that this is the method to use in this case.
精彩评论