Access to a socket outside socket.on ('connection') closure

Below is the app.js part, it has a socket connection with the client

io.sockets.on('connection', function (soc) { soc.emit('news', { status: 'connected' }); }); 

What I want to do is to access the social var outside of closing the connection, for example

 io.sockets.on('connection', function (soc) { do something magical here so I can access soc from outside }); soc.emit('news', { status: 'connected' }); 

What additional equipment should be added to the archive of this structure?

+4
source share
2 answers

you need to specify your io socket variable in the server code:

io.sockets.emit('news', { status: 'connected' });

so in your code example, it might look something like this:

 io.sockets.on('connection', function (soc) { emit(); }); function emit(){ io.sockets.emit('news', { status: 'connected' }); } 
+3
source

Perhaps you could try something like this:

 var foo; io.on('connection', function(soc){ foo = new Foo(soc); }); function Foo (socket){ this.emit = function () { if(socket) { socket.emit('msg'); } } } 

After someone is connected, you can call foo.emit();

This answer may help you: Do not emit a method installed outside of a socket connection

0
source

All Articles