TCP 端口竞争条件?
我想多次启动我的程序,并且每个实例都尝试使用 TCP 连接到同一服务器端口。我的目的是让第一个客户端连接,其他剩余的客户端应该尝试连接到不同的端口。
我使用此代码进行连接:
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...
}
}
现在第一个将成功连接,但第二个不会出现异常,但也未连接。如何判断程序是否真正连接?属性 tcp.Connected 不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当未真正连接时,连接的属性有时可能会返回 true。请参阅 msdn TcpClient.Connected:
我建议您 以编程方式检查以查看端口是否可用,而不是依赖异常。
为了让您变得非常简单,因为您不能依赖 Connected 标志,人们通常建议您使用此处找到的模式 TcpClient.Connected True,但未连接:
The connected property could sometimes return true, when its not really connected. See msdn TcpClient.Connected:
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: