Search code examples
node.jssocketsnetworkingeconnrefused

Node.js sending data to already started socket connection


I have a Server socket and a device which uses TCP long-connection mode.
They can connect and exchange data together. The node.js server is something like this:

net.createServer(function (socket) {
   console.log('ip:port' + socket.remoteAddress +':'+ socket.remotePort);
   socket.on('data', console.log);
}).listen(‘0.0.0.0’, 8888);

The device connects just right and I'm able to receive data from it. I can send commands to it by using the same process, by just doing socket.write('dothisplease') and this works too.

Now I have another worker process which should be sending commands at regular intervals. I can get ip and port from console.log when the device connects, it looks like: xx.xxx.xx.xxx:63024
I tried using this combination ip:port to create new connection:

var client = new net.Socket();
client.connect(device_port, device_ip, function () {
  client.write('dothisplease');
});

... but the result was ECONNREFUSED

  1. Is it right to use the same port to create a second connection to the device?
  2. Why does it work from the same process, but does not work from another?
  3. Eventually, can I pass the socket to another node Worker process. How?

Thanks a lot!


Solution

  • Your server is listening on port 8888. That's the port that all clients need to connect to. The client will also have to know what the server's IP address is in order to connect to it. A client uses a target IP address and target port to specify the destination for a TCP connection.

    socket.remotePort is not the port that anyone can connect on. That is the outgoing port that the first client used to connect to your server port. The outgoing port is a client bookkeeping thing that helps the client keep track of which network traffic belongs to which socket and is usually randomly assigned by the client.

    You read more about what remotePort is here.

    For reference, a TCP connection consists of two endpoints and each endpoint has an IP address and a port. The server will need to have a known IP address and a known port that all clients will use in order to connect to it. The client will already have its own IP address. Then, during the process of making a TCP connection to a server, the client will dynamically allocate an unused port number for the communication for this socket. That port number is used by the client to keep track of which network traffic belongs to which socket. This is not a port number that anyone can connect to.

    Is it right to use the same port to create a second connection to the device?

    No. You can't create a connection to a client. You can only create a connection to a listening server. And, you couldn't use the client's port that belongs to that other socket either.