node.js - How to access the target socket in a Socket.io handler -


i'm working socket.io server , i'm trying access socket emitted event client.

there's example in docs :

socket.on('private message', function (from, msg)  {     console.log('i received private message ', from, ' saying ', msg);    }); 

trying use this, i've noticed parameter order has changed in latest version , 'from' parameter function.

i'm having trouble using information emitted event.

is there way? or perhaps way using parameter info?

on server, code should in closure , can access parent function argument contains socket:

io.on('connection', function (socket) {   socket.emit('news', { hello: 'world' });   socket.on('my other event', function (data) {      // can access argument socket parent function     console.log(socket);     // access socket id of socket     console.log(socket.id);      console.log(data);   }); }); 

if want use named handler function, can create stub function passes socket named handler function this:

function myeventhandler(socket, data) {     // can access argument socket parent function     console.log(socket);     // access socket id of socket     console.log(socket.id);     console.log(data); }  io.on('connection', function (socket) {   socket.emit('news', { hello: 'world' });   socket.on('my other event', function (data) {     myeventhandler(socket, data); }); 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -