Reputation:
I want to write a peer to peer network application and have the following problem.
Two nodes in the network, A and B are trying to establish a connection to each other at the same time. When they both accept the connection of the other, there will be two TCP sockets opened.
Only one socket should be used for the communication between the two, because it is enough to communicate in both directions. What is an elegant solution to this problem?
Thanks!
Upvotes: 5
Views: 10555
Reputation: 598011
You should not be trying to establish two simultaneous connections at the same time. That is a flaw in your p2p design. The two peers need to coordinate with each other (such as by exchanging messages via a central server that they are both connected to and knows who they both are). A decision needs to be made first about who is listening and who is connecting. One peer only opens a listening socket and that info gets sent to the other peer so it knows where to connect. If that conection fails (ie, the listening peer is behind a NAT/firewall), the peers need to be notified and a decision made to swap roles. The previously-connecting peer now opens a listening socket and that info gets sent to the previously-listening peer so it knows where to connect. If that connection fails (ie, the now-listening peer is also behind a NAT/firewall), then a direct connection between the two peers is not possible without additional help (NAT hole punching, for instance). In some situations, a direct connection is simply not possible, so data being exchanged between them would have to be proxied through the central server.
Upvotes: 8