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

C#-TcpClient-无法建立连接,因为目标计算机主动拒绝它,c#,tcpclient,zebra-printers,C#,Tcpclient,Zebra Printers,您好,我目前正在创建一个新的连接与斑马打印机每分钟,它是正常工作5至8小时。之后,我得到了“由于目标机器主动拒绝,无法建立连接”错误。一旦出现此错误,在我完全关机并打开Zebra打印机电源之前,无法重新连接打印机 我没有正确关闭tcpClient steam,或者在大约300次重新连接后不会出现错误 我的代码: //CLASS MEMBERS private TcpClient client = new TcpClient(); private Timer TimZebraTimeOut; p

您好,我目前正在创建一个新的连接与斑马打印机每分钟,它是正常工作5至8小时。之后,我得到了“由于目标机器主动拒绝,无法建立连接”错误。一旦出现此错误,在我完全关机并打开Zebra打印机电源之前,无法重新连接打印机

我没有正确关闭tcpClient steam,或者在大约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视图:

建立新连接时,3个本地端口将递增


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

使用sysinternals中的tcpview查看windows认为您与打印机之间有多少连接。始终有2个在TimeWait中,1个在建立新连接时,所有端口号都会增加。我将在问题中添加图片。我将执行client.Dispose而不是client.client.Close。此外,我会在需要时打开连接(使用),然后关闭它。保持连接的时间不要超过您需要的时间我不能使用Using(),因为我需要提前验证连接是否已建立,并且我认为Close()已经调用Dispose(),我签入了.Net 4.7。框架引用源代码行449是否应该使用client.GetStream().close()显式关闭steam;TcpClient而非原始套接字上的调用关闭