enzom83
enzom83

Reputation: 8310

How can I avoid a double connection between two nodes?

I should simulate a p2p protocol (using Java) in which each node initially has established a connection with one neighbor. Then, using a discovery algorithm, each node finds new potential neighbors and it could connect with some of these.

Suppose that two nodes of the overlay network, such as A and B, are not neighbors each other: what happens if they find themselves at the same time? A sends a connection request to B while B sends a connection request to A, so that two TCP connection are established, but one of the two would be useless...

  1. Is there a way to avoid this problem?
  2. Alternatively, if the worst were to occur this problem, how can I find it unnecessary to drop the connection?

Assuming that each node has a unique ID, it would be sufficient to associate each connection with the IDs of the two neighbors, so that the node can locate and eliminate some duplicate connections. This could be a solution, but ... are there better solutions to break down any duplicate connections?

Upvotes: 2

Views: 216

Answers (2)

ARRG
ARRG

Reputation: 2486

One basic solution would be to make sure that opening an outbound connection and an inbound connection are operations that cannot be executed simultaneously. You can use concurrency primitives for this.

If these operations become sequential, then it is easy to avoid double links: keep track of all currently opened connections (inbound and outbound). Then when an inbound connection is requested, check whether there is already an outbound connection. If it is the case, refuse the new one.

Upvotes: 1

ciphor
ciphor

Reputation: 8288

You may use a hash table to store the connections on each node, using the unique ID as the hash key.

When a new connection (either outgoing or incoming) is established, you may check whether the peer node exists in the hash table, and use the new connection replacing the old one, to ensure no duplicated connections.

Upvotes: 1

Related Questions