Reputation: 532
If I create a server using this code:
var net = require('net');
server = net.createServer(function(sock){
/** some code here **/
});
server.listen(9000);
How do I access the socket outside of the callback function? This would help me to be able to create an array/list of sockets that I can store and access whenever I need to send data to a specific client.
I did have a weird workaround that I am currently using but I don't think this is the correct way. Basically I added socket to the server object by saying:
this.socket = sock
inside the callback function of createServer.
Then I can access it saying server.socket but this is only really useful if there is only one client.
To help better understand what I am trying to accomplish I have created a class that has a constructor function which holds this code:
this.server = net.createServer(this.handleConnection)
This class also has the method handleConnection to use as the callback. I also have a method called start which can be called with a port as a parameter to initiate server.listen(port).
What I want to accomplish is a method like below:
sendCommand(message, socket){
socket.write(message);
}
This way the server can send a message to the client from a function that is not within the callback function of createServer. Keep in mind that I am doing this from within a class so using the this keyword within the callback function accesses the net server object and not the class I created.
Every example I see is an extremely simple tcp server that only has one message sent from the server within the callback function. If anyone could shed some light on my problem that would be great thanks!
Upvotes: 3
Views: 1435
Reputation: 70
var net = require('net');
var listeners = [];
server = net.createServer(function(sock){
/** some code here **/
listeners.push(sock);
sock.on('close', function (){
var index = listeners.indexOf(sock);
if (index > -1) {
listeners.splice(index, 1);
}
});
});
server.listen(9000);
Upvotes: 1
Reputation: 250
I'm not sure if this is what you're after, but I would do something like this.
var net = require('net');
var conns = [];
var server = net.createServer(function(sock){
conns.push(sock);
sock.on('close', function (){
// TODO: Remove from conns
});
});
server.listen(9000);
Upvotes: 4