I am developing a peer-to-peer application in Rust and my goal is to only have one TCP connection (1 TcpStream) where to read from and write to. This is the example network shape:
It is important that every connection from a node to the others is from the same IP address and port. I am trying to implement a preliminary step to create all the connections and store them, to later both listen and write on them.
I have tried the following using the std::net::TcpStream
and std::net::TcpListen
:
Every node starts and listens for connections on their address (1.1.) and then connects to the others (1.2.). Result: all the nodes get block listening and none of them advances.
Every node listens for a connection from all the nodes with a lower index (2.1.) and creates a connection using
TcpStream::connect
for all the nodes with a greater index (2.2.), in separate threads. Result: The desired connection is established, but the connection createdTcpStream::connect
are from a random port.The same as 2., but create the connection (in 2.2.) using
socket2
library that allows to bind an address before connecting. Result: I obtain an error saying "Transport endpoint is already connected" after the second try to bind the socket.
Is this possible? In that case, how should I implement it?
I want to note that I plan on implementing a poll using mio
from all the sockets. Maybe this is an impediment to create the collection of sockets and read and write at the same time.
Please ask for any clarification if needed.