vinayr
vinayr

Reputation: 11244

how to use node.js upgrade event socket outside callback?

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();

Upvotes: 0

Views: 744

Answers (2)

meetamit
meetamit

Reputation: 25157

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).

Upvotes: 0

qwertymk
qwertymk

Reputation: 35294

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();

Upvotes: 1

Related Questions