Search code examples
c#tcpclientzebra-printers

C# - TcpClient - No connection could be made because the target machine actively refused it


Hi i am currently creating a new connection with a Zebra Printer every minute and it is working fine for 5 to 8 hours. After that I got the "No connection could be made because the target machine actively refused it" error. Once this error appears it is impossible to reconnect with the printer until i completely Shutdown and Power-up the Zebra printer.

I'm i not closing properly my tcpClient steam or what can't cause the error to appear after approximately 300 Reconnection

My Code :

//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);
}

Thanks a lot

Daniel


Netstat View :

Netstat View 1

When a new connection is established the 3 local Port are Incremented.

enter image description here


Solution

  • My Problem was that the Zebra printer have by default a connection timeout of 300 sec and i was creating a new connection each minute. After a short duration (6 Hours) i was overflowing the printer connection buffer. I Simply changed the printer timeout for 1 min and polled the printer to detect disconnection.