C# - TcpClient - 无法建立连接,因为目标计算机主动拒绝它

时间:2017-07-06 15:44:21

标签: c# tcpclient zebra-printers

您好我正在每分钟创建一个与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);
}

非常感谢

丹尼尔

Netstat查看:

Netstat View 1

建立新连接后,3个本地端口将增加。

enter image description here

1 个答案:

答案 0 :(得分:0)

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