An existing connection was forcibly closed by the remote host

I am working with a commercial application which is throwing a SocketException with the message,

An existing connection was forcibly closed by the remote host

This happens with a socket connection between client and server. The connection is alive and well, and heaps of data is being transferred, but it then becomes disconnected out of nowhere.

Has anybody seen this before? What could the causes be? I can kind of guess a few causes, but also is there any way to add more into this code to work out what the cause could be?

Any comments / ideas are welcome.

… The latest …

I have some logging from some .NET tracing,

System.Net.Sockets Verbose: 0 : [8188] Socket#30180123::Send() DateTime=2010-04-07T20:49:48.6317500Z

System.Net.Sockets Error: 0 : [8188] Exception in the Socket#30180123::Send - An existing connection was forcibly closed by the remote host DateTime=2010-04-07T20:49:48.6317500Z 

System.Net.Sockets Verbose: 0 : [8188] Exiting Socket#30180123::Send() -> 0#0

Based on other parts of the logging I have seen the fact that it says ‘0#0’ means a packet of 0 bytes length is being sent. But what does that really mean?

One of two possibilities is occuring, and I am not sure which,

1) The connection is being closed, but data is then being written to the socket, thus creating the exception above. The 0#0 simply means that nothing was sent because the socket was already closed.

2) The connection is still open, and a packet of zero bytes is being sent (i.e. the code has a bug) and the 0#0 means that a packet of zero bytes is trying to be sent.

What do you reckon? It might be inconclusive I guess, but perhaps someone else has seen this kind of thing?

12 Answers

This generally means that the remote side closed the connection (usually by sending a TCP/IP RST packet). If you’re working with a third-party application, the likely causes are:

  • You are sending malformed data to the application (which could include sending an HTTPS request to an HTTP server)
  • The network link between the client and server is going down for some reason
  • You have triggered a bug in the third-party application that caused it to crash
  • The third-party application has exhausted system resources

It’s likely that the first case is what’s happening.

You can fire up Wireshark to see exactly what is happening on the wire to narrow down the problem.

Without more specific information, it’s unlikely that anyone here can really help you much.

Using TLS 1.2 solved this error.
You can force your application using TLS 1.2 with this (make sure to execute it before calling your service):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 

Another solution :
Enable strong cryptography in your local machine or server in order to use TLS1.2 because by default it is disabled so only TLS1.0 is used.
To enable strong cryptography , execute these commande in PowerShell with admin privileges :

Set-ItemProperty -Path 'HKLM:SOFTWAREWow6432NodeMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:SOFTWAREMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord 

You need to reboot your computer for these changes to take effect.

This is not a bug in your code. It is coming from .Net’s Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.

    SocketError errorCode;
    int nBytesRec = socket.EndReceive(ar, out errorCode);
    if (errorCode != SocketError.Success)
        nBytesRec = 0;

Had the same bug. Actually worked in case the traffic was sent using some proxy (fiddler in my case). Updated .NET framework from 4.5.2 to >=4.6 and now everything works fine. The actual request was:
new WebClient().DownloadData("URL");
The exception was:

SocketException: An existing connection was forcibly closed by the remote host

Simple solution for this common annoying issue:

Just go to your “.context.cs” file (located under “” which located under your “*.edmx” file).

Then, add this line to your constructor:

public DBEntities() 
        : base("name=DBEntities") 
        this.Configuration.ProxyCreationEnabled = false; // ADD THIS LINE !

hope this is helpful.

I’ve got this exception because of circular reference in entity.In entity that look like

public class Catalog
    public int Id { get; set; }
    public int ParentId { get; set; }
    public Catalog Parent { get; set; }
    public ICollection<Catalog> ChildCatalogs { get; set; }

I added [IgnoreDataMemberAttribute] to the Parent property. And that solved the problem.

If Running In A .Net 4.5.2 Service

For me the issue was compounded because the call was running in a .Net 4.5.2 service. I followed @willmaz suggestion but got a new error.

In running the service with logging turned on, I viewed the handshaking with the target site would initiate ok (and send the bearer token) but on the following step to process the Post call, it would seem to drop the auth token and the site would reply with Unauthorized.

It turned out that the service pool credentials did not have rights to change TLS (?) and when I put in my local admin account into the pool, it all worked.

For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
    var buffer = new byte[1024];
    int read;

    while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
        await content.WriteAsync(buffer, 0, read);
        await content.FlushAsync();

After some time I found out the culprit was the buffer size, which was too small and didn’t play well with my weak Azure instance. What helped was to change the code to:

using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
    await remoteStream.CopyToAsync(content);

CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

“Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec.”

The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

I had the same issue and managed to resolve it eventually. In my case, the port that the client sends the request to did not have a SSL cert binding to it. So I fixed the issue by binding a SSL cert to the port on the server side. Once that was done, this exception went away.

I got the same issue while using .NET Framework 4.5. However, when I update the .NET version to 4.7.2 connection issue was resolved. Maybe this is due to SecurityProtocol support issue.

I had this issue when i tried to connect to postgresql while i’m using microsoft sutdio for mssql 🙂

This error occurred in my application with the CIP-protocol whenever I didn’t Send or received data in less than 10s.

This was caused by the use of the forward open method. You can avoid this by working with an other method, or to install an update rate of less the 10s that maintain your forward-open-connection.

Leave a Reply

Your email address will not be published. Required fields are marked *