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 conn开发者_如何学Pythonect:
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:
精彩评论