How to make a TCP connection between two servers if both can start a connection?

I have a certain number of servers that can process data locally in their own way. But after a while I want to synchronize some states that are common to each server. My idea was to establish a TCP connection from each server to other servers, such as a mesh network.

My problem is that in what order I make connections, since there is no "main" server, so each server is responsible for creating its own connections to each server there.

My idea was that each server connects, and if the connected server is already connected to the connecting server, just release the connection.

But how can I handle the fact that two servers are trying to connect at the same time? Because then I get 2 TCP connections instead of 1.

Any ideas?

+3
source share
3 answers

When connecting to the server, you will need a communication protocol so that you can check whether it is normal to start sending / receiving data, otherwise you can connect to one of the endpoints and immediately start sending data so that the other end cancels the connection.

To provide a single connection to the server, you just need something like this pseudocode:

remote_server = accept_connection()
lock mutex;
if(already_connected(remote_server)) {
  drop_connection(remote_server)
}
unlock mutex;

If your server is not multithreaded, you do not need locks to protect you when you check whether you are already connected, because there will be no problems at the same time.

, , .

, , , (, ) . , , , - .

0

. , , TCP- . . , , . , ( IP- UID), , , ( UID), .

+1

"LoadBalancer", , , , .

,

bool CreateConnection = (time()% == 0)

if (CreateConnection) {...}

- . time() , .

This ensures that you cannot connect two servers to each other at the same time. If you do not have identifiers for the servers, you can use a random value.

0
source

Source: https://habr.com/ru/post/1737292/


All Articles