0

I am using node.js connect framework to listen to upgrade event. I can use the socket in callback function to write back to client. But how can I use the socket outside callback function to write to same client. In my case there is only one client connected to server.

app.on('upgrade', function(req, socket) {
    socket.write('hello');    
});

function sendEvent()
{
 // how to use socket here??
}

sendEvent();
aynber
  • 22,380
  • 8
  • 50
  • 63
vinayr
  • 11,026
  • 3
  • 46
  • 42

2 Answers2

1

Try saving the socket for later use (ie outside the app.on() function):

var socket;

app.on('upgrade', function(req, sock) {
    socket = sock;
    socket.write('hello');
});

function sendEvent() {
    socket.write('hi!');
}

sendEvent();
qwertymk
  • 34,200
  • 28
  • 121
  • 184
0

If:

  • really only one client is ever connected to this server, OR
  • there are multiple clients connected, but it's ok for all of them to receive the event

Then you can use

sockets.emit("some_event")

which would broadcast to all connected clients (or 1 client in your case).

meetamit
  • 24,727
  • 9
  • 57
  • 68