Alexander Mills
Alexander Mills

Reputation: 100320

TCP client making first connection

Say I have a Node.js TCP client

https://nodejs.org/api/net.html#net_socket_connect_path_connectlistener

I have a library, and the library takes an array of host/port combinations to connect to. I want the client to make only one connection.

const endpoints = [
 {host: h1, port: p1},
 {host: h2, port: p2},
 {host: h3, port: p3},
];

How can an I implement a simple mechanism to try connecting to these?

My guess is that the simplest way is to connect to them serially, one by one, until first connection.

What I am concerned about, is clients that are connected somehow to two different endpoints. Is that possible?

Upon second thought - it seems no better or safer to try to connect them serially with a timeout, then to try to connect to them all in parallel. It just seems to be a matter of properly cleaning up connections or half-connections that you don't need after first "real" connection.

Upvotes: 0

Views: 70

Answers (1)

user1837296
user1837296

Reputation: 596

I believe that generally, each connection lasts only long enough to send a single request and get the response to it. So connecting to multiple endpoints is indeed possible; if you want to connect to only one, you'd need to connect serially. (Or you could connect asynchronously and simply "accept" the first to respond, though then you'd get that first connection attempt even to the ones that don't get accepted; whether that's a problem or not depends on why you want to connect to only one.)

Upvotes: 1

Related Questions