title: TcpClient for Zebra Not Disconnecting: "No connection could be made because the target machine actively refused it."
body: <p>I am using <code>TcpClient</code> to connect to a Zebra label printer, then send a glob of ZPL code, then disconnect, repeat. This continues for dozens of labels.</p>
  
  <p>The code that print a single label is as follows:</p>
  
  <pre><code>client = new TcpClient();                      
  client.Connect(networkAddress, port);          
  writer = new StreamWriter(client.GetStream()); 
  writer.Write(content);                         
  writer.Flush();                                
  
  if (client.Client.Connected)                   // Excessive levels of unnecessary
      client.Client.Disconnect(false);           //   disconnecting and disposing 
  client.Close();                                //   for testing purposes
  writer.Close();
  writer.Dispose();
  </code></pre>
  
  <p>After a couple dozen labels print, I get this exception:</p>
  
  <pre><code>No connection could be made because the target machine actively refused it.
  </code></pre>
  
  <p>I run <code>netstat</code> and see that I'm maintaining a couple dozen <code>TIME_WAIT</code> status connections to the printer, each on a different local port. <code>TIME_WAIT</code> means my machine has tried to disconnect but the printer is waiting to see if there are any remaining packets to be sent.</p>
  
  <p>What is standard operating procedure for this? I don't think I can wait until the time period elapses because I think that's in the minutes. I changed the code to this to reuse the socket:</p>
  
  <pre><code>//client = new TcpClient();
  client.Connect(networkAddress, port);          
  writer = new StreamWriter(client.GetStream()); 
  writer.Write(content);                         
  writer.Flush();                                
  
  if (client.Client.Connected)
      client.Client.Disconnect(true); // Changed to true
  //client.Close();
  writer.Close();
  writer.Dispose();
  </code></pre>
  
  <p>But I get this error the second time I iterate over <code>client.Connect()</code>.</p>
  
  <pre><code>A connect request was made on an already connected socket.
  </code></pre>
  
  <p>What's a handsome fellow such as myself to do in this situation?</p>