Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs How to access a tcp socket outside the callback function

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!

like image 467
Rudy Garcia Avatar asked Sep 20 '26 17:09

Rudy Garcia


2 Answers

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);
like image 90
fresla Avatar answered Sep 22 '26 07:09

fresla


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);
like image 38
al3x1s Avatar answered Sep 22 '26 06:09

al3x1s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!