gpt4 book ai didi

c# - TcpClient.Connect 说 "A connection attempt failed because the connected party..."

转载 作者:行者123 更新时间:2023-11-30 22:28:36 28 4
gpt4 key购买 nike

我有一个在 Windows XP SP3 x86 上运行的 Visual Studio 2008 C# .NET 3.5 应用程序。在我的应用程序中,我有一个事件处理程序 OnSendTask 可以同时被多个线程调用。它打开到远程主机的 TCP 连接并发送/接收数据。

例如:

/// <summary>
/// prevent us from exceeding the maximum number of half-open TCP
/// connections in Windows XP.
/// </summary>
private System.Threading.Semaphore tcp_connection_lock_ =
new System.Threading.Semaphore(10, 10);

public event EventHandler<SendTaskEventArgs> SendTask;

private void OnSendTask(object sender, SendTaskEventArgs args)
{
try
{
tcp_connection_lock_.WaitOne();
using (TcpClient recipient = new TcpClient())
{
// error here!
recipient.Connect(args.IPAddress, args.Port);
using (NetworkStream stream = recipient.GetStream())
{
// read/write data
}
}
catch
{
// write exceptions to the logfile
}
finally
{
tcp_connection_lock_.Release();
}
}

void SendTasks(int tasks_to_send)
{
using (ManualResetEvent done_event = new ManualResetEvent(false))
{
int countdown = tasks_to_send;
for (int i = 0; i < tasks_to_send; ++i)
{
ThreadPool.QueueUserWorkItem((o) =>
{
SendTaskEventArgs args = new SendTaskEventArgs(/*...*/);

EventHandler<SendTaskEventArgs> evt = SendTask;
if (evt != null)
evt(this, e);

if (Interlocked.Decrement(ref countdown) == 0)
done_event.Set();
}, i);
}
done_event.WaitOne();
}
}

不幸的是,我偶尔会看到这个错误:

System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.16:59596
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)

一些信息点:

  • 如果我向 40 个 Remote 发送任务,我会看到来自大约 6 个 Remote 的响应。
  • Wireshark 跟踪显示甚至没有尝试启动从 PC 到远程的 TCP 连接。
  • 我可以从 PC ping Remote 并获得一致的良好响应。
  • Remote 都与运行此应用程序的 PC 位于同一交换机和子网上。没有花哨的网络。

任何人都可以建议可能导致此错误的原因或我该如何解决它吗?

谢谢

最佳答案

我不确定最大半开 TCP 连接背后的所有细节,但我相信它不是特定于应用程序连接,而是系统范围的。您确定发生此错误时系统上没有其他应用程序正在创建 TCP 连接吗?

每当发生错误时,我都会设置重试。像这样的东西:

private const int MaxRetries = 10;
private void OnSendTask(object sender, SendTaskEventArgs args)
{
bool retry = false;
try
{
tcp_connection_lock_.WaitOne();
using (TcpClient recipient = new TcpClient())
{
// error here!
recipient.Connect(args.IPAddress, args.Port);
using (NetworkStream stream = recipient.GetStream())
{
// read/write data
}
}
}
catch (SocketException ex)
{
if(args.RetryCount < MaxRetries)
{
retry = true;
args.RetryCount++;
}
else
{
// write exceptions to the logfile
}
}
finally
{
tcp_connection_lock_.Release();
}

if(retry)
{
Thread.Sleep(1);
OnSendTask(sender, args);
}
}

关于c# - TcpClient.Connect 说 "A connection attempt failed because the connected party...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704436/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com