简体   繁体   中英

TCP port race condition?

I want to start my program multiple times and each instance tries to connect with TCP to the same server port. What I intend is to let the first one connect and the other remaining clients should try to connect to a different port.

I use this code to connect:

TcpClient tcp;
StreamReader streamReader;
StreamWriter streamWriter;

bool success=false;
while (!success) {
  try
  {
    tcp = new TcpClient(Hostname, currentPort);

    streamReader = new StreamReader(tcp.GetStream());
    streamWriter = new StreamWriter(tcp.GetStream());
    success=true;
  } catch {
    // wait a bit...
  }
}

Now the first one will connect succesfully but the second one doesn't get an exception but also isn't connected. How can I determine if a program is really connected? The property tcp.Connected didn't work.

The connected property could sometimes return true, when its not really connected. See msdn TcpClient.Connected :

Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions

I would suggest you programaticaly check to see if the port is available, instead of relying on exceptions.

And to make it really simple for you, since you can't rely on the Connected flag, people generally suggest you use a pattern found here TcpClient.Connected True, yet not connected :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM