Reputation: 380
Is there any way to find a socket's namespace or client URL when it connects to the server?
Client:
var socket = io.connect('/ns1');
Server:
io.sockets.on('connection', function(socket){
//socket.something.namespace?
});
I've looked through the object structure of the socket extensively but any reference to namespaces just has "name" : "/" or lists all the server's namespaces and not the single socket's namespace.
Same thing with URL as well.. I've only been able to find it in headers referrer but that might not be as robust as a true URL reference.
Upvotes: 0
Views: 1046
Reputation: 1526
The socket.io guide uses this way to listen for a conneciton on a namespace:
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
console.log('someone connected'):
});
It also refers to "io.sockets" as the default namespace. So when the "io.sockets.on('connection'" method is fired you are in the default namespace. Related
Edit: Receiving connections from dynamically created namespaces works pretty straightforward as well. I think this solves your initial question.
Another edit: The namespace is of course also accessable in the socket this.nsp.name
:
function registerNamespace(name){
var nsp = io.of(name);
nsp.on('connection', function(socket){
console.log("I am in namespace: " + this.name);
socket.on('hello', function () {
console.log("Hello in namespace: " + this.nsp.name);
});
socket.on('disconnect', function () {
console.log("I was in namespace: " + this.nsp.name);
});
});
}
registerNamespace("/name2");
registerNamespace("/name1");
Upvotes: 2