C# An established connection was aborted by the software in your host machine

C#SocketsNetwork Programming

C# Problem Overview


These errors are getting more and more frequent on my Game Server. They are causing the server to keep closing and restarting...

System.Net.Sockets.SocketException (0x80004005): An established connection was aborted by the software in your host machine 
   at System.Net.Sockets.Socket.BeginSend(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state) 
   at iRP.Game.Sessions.Session.SendData(Byte[] Data)

This is the code from which these errors are generated:

public void SendData(byte[] Data)
{
    try
    {
        if (mSocket == null)
        {
            //Output.WriteLine("[SND] Socket has a null exception, which means it is now invalid. Remove this socket!", OutputLevel.CriticalError);
        }
        else
        {
            mSocket.BeginSend(Data, 0, Data.Length, SocketFlags.None, sendCallback, mSocket);
        }
    }
    catch (Exception e)
    {
        string WhatToWrite = "Error handled (SESSION): " + e.ToString() + "\n\n" + e.Message + "\n\nStack: " + e.StackTrace + Environment.NewLine + "\n\n";
        File.AppendAllText(Environment.CurrentDirectory + "\\data\\fatal.txt", WhatToWrite);
        Program.Stop();
    }
}

The buffer sizes are correctly set, we are using KeepAlive on the socket and were using Send and Receive Timeouts.

People suggested that disabling the firewall would help, but whenever I do this our Game Server (Dedicated Server) restarts itself as if it's under attack, so the firewall must remain enabled.

Anyone else got any other solutions for this?

PS: We are behind DDoS Mitigation Services which may be limiting the number of connections...

C# Solutions


Solution 1 - C#

> An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Solution 2 - C#

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

Solution 3 - C#

Could be related to the maximum number of concurrent requests. I was able to fix it with two solutions:

  • Increase the default limit of the max concurrent connections (by default it is set to 2):
ServicePointManager.DefaultConnectionLimit = 25
  • Wrap sending requests around a buffer: could use ConcurrentQueue to limit the rate, or implement a simple wait as the following:
while (activeRequests >= maxConcurrentRequests)
    Thread.Sleep(1000);

Interlocked.Increment(ref activeRequests);
var response = await _client.GetStreamAsync(endpoint);
Interlocked.Decrement(ref activeRequests);

Solution 4 - C#

While the answer from Hans is an excellent high level summary of the error that worked great for getting me started, I ended up finding a page that explained the root cause well enough that I was able to recreate it with a python script.

The page presents a couple different descriptions of this error that are more detailed than the "connection was aborted" paraphrasing from Hans's answer but still pretty cryptic and not very informative.

The post then explains this scenario that would produce the error:

> An HTTP POST is to be sent to an HTTP server. The server begins reading the POST and notices that the HTTP request header is invalid. It immediately sends an HTTP response (with an error status, perhaps status=400) and closes the connection without trying to continue reading the remainder of the HTTP request that is forthcoming. > >Meanwhile, the client is still happily writing the remainder of the HTTP request to the socket. (Remember a TCP/IP socket connection needs to be closed from both sides. In this case, the server has closed its side, but the client is still pumping data into the half-open connection.) The client finishes writing the HTTP POST to the socket — meaning that data has been buffered to Winsock. The client application then tries to read the HTTP response, but it cannot because the outgoing retransmission (of the buffered data by WinSock) failed and the socket connection was shutdown on the client side (by Winsock). Even though the HTTP server sent the response, it is lost and cannot be retrieved. The error your application will receive when trying to read the HTTP response on the socket is WSAECONNABORTED

Wikipedia also has a page to explain what winsock is, but all you really need to know for this scenario is that its the Windows socket API.

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
QuestionRichard WilliamsView Question on Stackoverflow
Solution 1 - C#Hans PassantView Answer on Stackoverflow
Solution 2 - C#yacineView Answer on Stackoverflow
Solution 3 - C#HamedView Answer on Stackoverflow
Solution 4 - C#MoralCodeView Answer on Stackoverflow