86

What is the correct way to close or reset a TcpClient connection? We have software that communicates with hardware but sometimes something goes wrong and we are no longer to communicate with it, until we restart the software.

I have tried forcing TcpClient.Close() and even setting it to null but that doesn't work. Only a complete restart of the software works.

Suggestions?


I can't use the using keyword because TpcClient is only defined in one location, but used throughout the library. (And there is only one connection at any given time)

It's a library that handles communication. The software itself can call the ResetConnection() method of the Controller class (which represents the hardware).

It currently looks like

if (tcpClient != null)
{
    tcpClient.Close();
    tcpClient = null;
}

Now from what I've read here I should use tcpClient.Dispose() instead of " = null"

I'll give that a try and see if it makes a difference.

9 Answers 9

100

You have to close the stream before closing the connection:

tcpClient.GetStream().Close();
tcpClient.Close();

Closing the client does not close the stream.

9
  • 14
    If closing the TcpClient doesn't close the connection, what the hell does it close? Is there any reason to close the TcpClient?
    – Qwertie
    Mar 22, 2011 at 15:20
  • I really don't know, you should check with Reflector, but it probably closes other objects used rather than the stream (maybe the stream can be shared between different objects and that's why its not automatically closed, just guessing). Mar 22, 2011 at 16:39
  • 44
    Note that bug (support.microsoft.com/kb/821625) that made it necessary to close the stream only exists in .NET 1.1 and earlier. I tested out the sample code in .NET 4.5, and it works fine without calling close on the stream.
    – Anssssss
    Jan 2, 2014 at 15:56
  • 5
    I still get intermittent problems on .NET 4.6.1 if I use tcpClient.Close() instead of tcpClient.Client.Close() or tcpClient.GetStream().Close(). I almost lost my mind the other day until I found this. Jul 1, 2016 at 10:24
  • With .NET Standard's System.Net.Sockets.TcpClient, call Dispose(). There is no Close() method. Apr 4, 2017 at 21:53
31

Given that the accepted answer is outdated and I see nothing in the other answers regarding this I am creating a new one. In .Net 2, and earlier, you had to manually close the stream before closing the connection. That bug is fixed in all later versions of TcpClient in C# and as stated in the doc of the Close method a call to the method Close closes both the connection and the stream

EDIT according to Microsoft Docs

The Close method marks the instance as disposed and requests that the associated Socket close the TCP connection. Based on the LingerState property, the TCP connection may stay open for some time after the Close method is called when data remains to be sent. There is no notification provided when the underlying connection has completed closing.

Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.

6
  • @Twometer which version of .Net are you targeting? Nov 5, 2018 at 8:57
  • it's .NET 4.6.1
    – Twometer
    Nov 5, 2018 at 8:59
  • I am calling TcpClient.Close(), tcpClient.Client.Close(), .Disconnect() whatever and it doesn't close. Only when I kill the process, the server says "Connection closed"
    – Twometer
    Nov 5, 2018 at 9:00
  • The example in the article you linked still calls networkStream.Close(); before calling tcpClient.Close();, so either the example is out of date or you still have to manually close the underlying stream.
    – Deantwo
    Nov 5, 2018 at 13:42
  • @Deantwo Updated my answer. It marks it as ready to be disposed. No guarantee on when it will be disposed though. Nov 6, 2018 at 9:50
22

Use word: using. A good habit of programming.

using (TcpClient tcpClient = new TcpClient())
{
     //operations
     tcpClient.Close();
}
5
  • 48
    Not applicable in all models. This is great if you are using the connection temporarily within one code block but if you have a client implementation that wants to maintain a connection as a member, this method will fail. You will also find that, as per the class documentation, calling Dispose() on the TcpClient does not close the underlying socket. Using will only dispose.
    – Gusdor
    Nov 18, 2011 at 16:30
  • 1
    This is not gonna work in async and non-blockign sockets, And actully this code can not be used if you want to store the connection somewhere and manage it.
    – Kas
    Jul 9, 2013 at 7:06
  • 7
    @Gusdor Looking at the reflected source, it does seem that Dispose(true) will call Close() on the client. (.NET 4.0)
    – dtroy
    Aug 13, 2013 at 1:47
  • Must be a new addition. I posted in reference to .net 3.5. Well spotted!
    – Gusdor
    Aug 13, 2013 at 6:58
  • 1
    @Dermot, @SteveJobs well, now that the future is here with the async keyword, it does ;-). It would even be compatible with BeginConnect() and EndConnect(), provided you call End… inside the using block…
    – binki
    Nov 27, 2015 at 15:38
12

Despite having all the appropriate using statements, calling Close, having some exponential back off logic and recreating the TcpClient I've still been seeing issues where the application cannot recover the TCP connection without an application restart. It keeps failing with a System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

But there is an option LingerState on the TcpClient that appears it may have solved the issue (might not know for a few months as my own hardware setup only fails about that often!). See MSDN.

// This discards any pending data and Winsock resets the connection.
LingerOption lingerOption = new LingerOption(true, 0);

using (var tcpClient = new TcpClient 
       {SendTimeout = 2000, ReceiveTimeout = 2000, LingerState = lingerOption })
   ...
2
  • Hi! I have exactly the same problem, despite having all the appropiate code sometimes this exception appears at random times, the LingerOption solved your issue? I'm thinking seriously to migrate all my code to UDP just to get rid of this intermittent problem
    – Rafael
    May 21, 2019 at 17:59
  • @rafael I think it has solved my problem: I have not seen this issue at all since posting this.
    – Ian Mercer
    May 22, 2019 at 2:12
8

Except for some internal logging, Close == Dispose.

Dispose calls tcpClient.Client.Shutdown( SocketShutdown.Both ), but its eats any errors. Maybe if you call it directly, you can get some useful exception information.

8

The correct way to close the socket so you can re-open is:

tcpClient.Client.Disconnect(true);

The Boolean parameter indicates if you want to reuse the socket:

Disconnect method usage

7

Closes a socket connection and allows for re-use of the socket:

tcpClient.Client.Disconnect(false);
4
  • 1
    I am confused about why I need to do this if I want to later re-open the connection. Simply closing streams & closing the TcpClient then throws an exception on a later .Connect.
    – p e p
    Jun 10, 2015 at 13:37
  • 6
    Don't you mean Disconnect(true) ?
    – WDUK
    Dec 12, 2017 at 3:54
  • 1
    @WDUK I thought so too, but if you use disconnect(true) the socket can hang waiting to be reused..... it's easier to set to false then make another socket another time.
    – rupweb
    Mar 8, 2022 at 16:56
  • Good to know, thanks!
    – WDUK
    Mar 11, 2022 at 7:55
2
client.Dispose();
client.Close();
 if (stream != null)
    {
      clientstream.Dispose();
      clientstream.Close();
     }
1

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

4
  • There is only one connection, and I closed it but I did not dispose it... does that make a difference? (I suppose it does, just asking :-)
    – TimothyP
    Jan 8, 2009 at 18:32
  • TcpClient.Dispose is protected and cannot be called directly. Oct 21, 2014 at 19:55
  • @theycallmemorty doc says otherwise. msdn.microsoft.com/en-us/library/vstudio/…
    – chakrit
    Oct 22, 2014 at 6:44
  • 2
    It's an explicit interface implementation. So it's not visible tot he type TcpClient until it's cast to IDisposable, ie, ((IDisposable)client).Dispose() Mar 11, 2015 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.