TCP 端口竞争条件?

发布于 2024-11-01 22:38:31 字数 532 浏览 7 评论 0原文

我想多次启动我的程序,并且每个实例都尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

¢蛋碎的人ぎ生 2024-11-08 22:38:31

当未真正连接时,连接的属性有时可能会返回 true。请参阅 msdn TcpClient.Connected

由于 Connected 属性仅反映最近操作时的连接状态,因此您应该尝试发送或接收消息来确定当前状态。消息发送失败后,该属性不再返回true。请注意,此行为是设计使然。您无法可靠地测试连接的状态,因为在测试和发送/接收之间的时间内,连接可能已丢失。您的代码应该假设套接字已连接,并妥善处理失败的传输

我建议您 以编程方式检查以查看端口是否可用,而不是依赖异常。

为了让您变得非常简单,因为您不能依赖 Connected 标志,人们通常建议您使用此处找到的模式 TcpClient.Connected True,但未连接

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:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文