An existing connection was forcibly closed by the remote host

C#.NetNetworkingSockets

C# Problem Overview


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 occurring, 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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord 

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

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

Simple solution for this common annoying issue:

Just go to your ".context.cs" file (located under ".context.tt" 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.

Solution 6 - C#

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.

Solution 7 - C#

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.

Solution

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.

Solution 8 - C#

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.

Solution 9 - C#

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.

Solution 10 - C#

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.

Solution 11 - C#

I had this issue when i tried to connect to postgresql while i'm using microsoft sutdio for mssql :)

Solution 12 - C#

We are using a SpringBoot service. Our restTemplate code looks like below:

@Bean
    public RestTemplate restTemplate(final RestTemplateBuilder builder) {

        return builder.requestFactory(() -> {
            final ConnectionPool okHttpConnectionPool =
                    new ConnectionPool(50, 30, TimeUnit.SECONDS);
            final OkHttpClient okHttpClient =
                    new OkHttpClient.Builder().connectionPool(okHttpConnectionPool)
                            // .connectTimeout(30, TimeUnit.SECONDS)
                            .retryOnConnectionFailure(false).build();

            return new OkHttp3ClientHttpRequestFactory(okHttpClient);
        }).build();
    }

All our call were failing after the ReadTimeout set for the restTemplate. We increased the time, and our issue was resolved.

Solution 13 - C#

For me, it was because the app server I was trying to send email from was not added to our company's SMTP server's allowed list. I just had to put in SMTP access request for that app server.

This is how it was added by the infrastructure team (I don't know how to do these steps myself but this is what they said they did):

1.  Log into active L.B.
2.  Select: Local Traffic > iRules > Data Group List
3.  Select the appropriate Data Group
4.  Enter the app server's IP address
5.  Select: Add
6.  Select: Update
7.  Sync config changes

Solution 14 - C#

Yet another possibility for this error to occur is if you tried to connect to a third-party server with invalid credentials too many times and a system like Fail2ban is blocking your IP address.

Solution 15 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeterView Question on Stackoverflow
Solution 1 - C#RarrRarrRarrView Answer on Stackoverflow
Solution 2 - C#willmazView Answer on Stackoverflow
Solution 3 - C#cagatayView Answer on Stackoverflow
Solution 4 - C#0x49D1View Answer on Stackoverflow
Solution 5 - C#ayheberView Answer on Stackoverflow
Solution 6 - C#Bazaleev NikolaiView Answer on Stackoverflow
Solution 7 - C#ΩmegaManView Answer on Stackoverflow
Solution 8 - C#iefgnoixView Answer on Stackoverflow
Solution 9 - C#Andrej LucanskyView Answer on Stackoverflow
Solution 10 - C#ChamizView Answer on Stackoverflow
Solution 11 - C#Abdullah TahanView Answer on Stackoverflow
Solution 12 - C#GayathriView Answer on Stackoverflow
Solution 13 - C#Ash KView Answer on Stackoverflow
Solution 14 - C#0xcedView Answer on Stackoverflow
Solution 15 - C#BelekzView Answer on Stackoverflow