randy
randy

Reputation: 1877

getting access to the socket on a listen outside the connection callback in node

I have a node app that is both a socket client and server

it has

var frame_io = require('socket.io');
frame_io.listen(server).on('connection', function (socket) {
    socket.on('join', function(data) {
          //do stuff
    });
});

var io = require('socket.io-client');
var socket = io.connect('http://' + host + ':' + port, {
    reconnect: true
});

then i have :

socket.on('sync', function (msg) {
      //emit something to frame_io
});

on the sync i need to now fire an emit to the socket within the frame_io.listener and i am wondering the best way to do that

thanks

Upvotes: 2

Views: 682

Answers (1)

hbillings
hbillings

Reputation: 174

Try this one out:

var serverSocket;
var frame_io = require('socket.io');
frame_io.listen(server).on('connection', function (socket) {
    serverSocket = socket;
    socket.on('join', function(data) {
          //do stuff
    });
});

var io = require('socket.io-client');
var socket = io.connect('http://' + host + ':' + port, {
    reconnect: true
});

socket.on('sync', function (msg) {
    //emit something to frame_io
    serverSocket.emit('thing');
});

Just take the passed in socket and pull it out and store it globally in the file.

Upvotes: 2

Related Questions