TcpClient.Connect说“连接尝试失败,因为连接方......”

时间:2012-05-22 14:48:32

标签: c# .net-3.5 tcpclient

我有一个在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个遥控器,我会在6周左右看到这个响应。
  • Wireshark跟踪显示甚至没有尝试启动从PC到远程的TCP连接。
  • 我可以从PC上ping远程控制器并获得一致的良好响应。
  • 遥控器与运行此应用程序的PC位于同一个交换机和子网中。在路上没有花哨的网络。

有人可以提出可能导致此错误的原因或我如何修复错误吗?

由于

1 个答案:

答案 0 :(得分:2)

我不确定最大半开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);
    }
}