0

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.

kmp
  • 10,535
  • 11
  • 75
  • 125
Michael
  • 37
  • 1
  • 6
  • You should see this post. http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available – Nix Apr 16 '11 at 15:01
  • @Nix: Yes, I'm using this code already but there is still a race condition as both programms try to connect after they got the information that the port is available. – Michael Apr 16 '11 at 15:07

1 Answers1

0

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:

Community
  • 1
  • 1
Nix
  • 57,072
  • 29
  • 149
  • 198