accessing socket outside the socket.on('connection') closure

express, node.js, socket.io

Solution

you need to reference your socket io variable in your server code:

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

so in your sample code, it could look something like this:

io.sockets.on('connection', function (soc) {
    emit();
});

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

Problem

Below is part of app.js, it has socket connection with client ``` io.sockets.on('connection', function (soc) { soc.emit('news', { status: 'connected' }); }); ``` What I want to do is access the soc var outside the connection closure, like this ``` io.sockets.on('connection', function (soc) { do something magical here so I can access soc from outside }); soc.emit('news', { status: 'connected' }); ``` What additional technique need to add in to archive this structure?

Original source