title: C# - TcpClient - No connection could be made because the target machine actively refused it
body: <p>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.</p>
  
  <p>I'm i not closing properly my tcpClient steam or what can't cause the error to appear after approximately 300 Reconnection  </p>
  
  <p>My Code : </p>
  
  <pre><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);
  }
  </code></pre>
  
  <p>Thanks a lot</p>
  
  <p>Daniel</p>
  
  <hr>
  
  <p>Netstat View : </p>
  
  <p><a href="https://i.stack.imgur.com/sTZIo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sTZIo.png" alt="Netstat View 1"></a></p>
  
  <p>When a new connection is established the 3 local Port are Incremented.</p>
  
  <p><a href="https://i.stack.imgur.com/uq3j6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uq3j6.png" alt="enter image description here"></a></p>