【问题标题】:C# - TcpClient - No connection could be made because the target machine actively refused itC# - TcpClient - 无法建立连接,因为目标机器主动拒绝它
【发布时间】:2017-07-12 08:43:11
【问题描述】:

您好,我目前每分钟都在与 Zebra 打印机建立一个新连接,它可以正常工作 5 到 8 个小时。之后我得到“无法连接,因为目标机器主动拒绝它”错误。一旦出现此错误,在我完全关闭并启动 Zebra 打印机之前,无法重新连接打印机。

我没有正确关闭我的 tcpClient 蒸汽,或者在大约 300 次重新连接后不会导致错误出现

我的代码:

//CLASS MEMBERS
private TcpClient client = new TcpClient(); 
private Timer TimZebraTimeOut;
private int ZebraTimeOutTime = 60000;
private bool NewConnectionNeeded = true;

//NORMALY CALLED IN CONSTRUCTOR
TimZebraTimeOut = new Timer(TimZebraTimeOutCallback, null,this.ZebraTimeOutTime, Timeout.Infinite);

//CLASS METHODS
private void CreateNewConnectionIfComTimeOut
{
    try
    {
        if (this.NewConnectionNeeded ) // If time is out Create new connection with Zebra Printer
        {
            //Close last connexion open
            client.Client.Close();
            //Create a new one
            client = new TcpClient();
            // Add Read/Write TimeOut
            client.SendTimeout = 10000;
            client.ReceiveTimeout = 10000;                    
            //Create TCP Connection
            client.Connect(this.config.IpAddress, this.config.Port);
            // Connection with PrinterEstablished
            this.NewConnectionNeeded = false; 
            this.iLog.Info("CommunicationWithZebraPrinter : New connection With Labeler Established "); // If New connection not caused by timeout

        }
    }
    catch (Exception exception)
    {
        // Write exception in Log 
        this.iLog.Error("CommunicationWithZebraPrinter : Can't establish a connection with printer: " + exception.Message.ToString());
    }
}

// Zebra Communication Timer interrupt callback function
private void TimZebraTimeOutCallback(Object state)
{
    // Flag That ZebraCom have timeout
    this.NewConnectionNeeded= true;
    //Restart Zebra Com TimeOut 
    TimZebraTimeOut.Change(this.ZebraTimeOutTime, Timeout.Infinite);
}

非常感谢

丹尼尔


网络统计视图:

当建立新连接时,3 个本地端口会增加。

【问题讨论】:

  • 使用 sysinternals 中的 tcpview 来查看窗口认为从您到打印机的连接数
  • TimeWait 中总是有 2 个,Established 中总是有 1 个,当创建新连接时,所有端口号都会递增。我将在我的问题中添加图片。
  • 我会做 client.Dispose 而不是 client.Client.Close。此外,我会在需要时打开连接(使用),然后关闭它。保持连接的时间不要超过您的需要
  • 我不能使用 Using(),因为我需要提前验证连接是否已建立,并且我认为 Close() 已经调用了 Dispose(),我签入了 .Net 4.7。框架参考源代码 Line 449 referencesource.microsoft.com/#System/net/System/Net/Sockets/… 我是否应该使用 client.GetStream().Close() 显式关闭 Steam;
  • 在 TcpClient 上调用 close 而不是在原始套接字上

标签: c# tcpclient zebra-printers


【解决方案1】:

我的问题是 Zebra 打印机默认连接超时为 300 秒,我每分钟创建一个新连接。在短暂的持续时间(6 小时)后,我溢出了打印机连接缓冲区。我只是将打印机超时时间更改为 1 分钟,然后轮询打印机以检测断开连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2011-08-24
    • 2023-03-25
    • 2021-05-05
    • 2015-04-05
    • 2016-12-08
    相关资源
    最近更新 更多