Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 471
angry kiwi Avatar asked May 01 '13 08:05

angry kiwi


1 Answers

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' });
}
like image 171
alazzaro Avatar answered Oct 04 '22 23:10

alazzaro