How to solve "An existing connection was forcibly closed by a remote host." error?

Rozerin Yıldız 21 Reputation points
2022-08-12T13:00:08.423+00:00

I am trying to connect the server using ASP.Net Core 6. When I run it on my localhost it works fine, but when I publish on the server I get an error. I published my Server project to FileZilla. IP address, and port are correct. However, i got this error message:

Blockquote

Socket connected.
Sent 19 bytes to server.
System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by a remote host. at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Int32>.GetResult(Int16 token) at System.Threading.Tasks.ValueTask`1.ValueTaskSourceAsTask.<>c.<.cctor>b__4_0(Object state) --- End of stack trace from previous location --- at System.Threading.Tasks.TaskToApm.EndTResult at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult) at AsynchronousClient.ReceiveCallback(IAsyncResult ar) in C:\Users\rozer\source\repos\Client1\Client1\Program.cs:line 129

The error line:

'''
int bytesRead = client.EndReceive(ar);
'''

I understood that the connection has been made. But ı do not understand why it is forcibly closed by a remote host and I got this error. Is it about a firewall issue or something like that? And how can i solve this problem? In some of our research, we have seen suggestions that TLS should be configured correctly. How can we do this?

This is the client project:

   using System;  
   using System.Net;  
   using System.Net.Sockets;  
   using System.Threading;  
   using System.Text;  
     
   // State object for receiving data from remote device.    
   public class StateObject  
   {  
       // Client socket.    
       public Socket workSocket = null;  
       // Size of receive buffer.    
       public const int BufferSize = 256;  
       // Receive buffer.    
       public byte[] buffer = new byte[BufferSize];  
       // Received data string.    
       public StringBuilder sb = new StringBuilder();  
   }  
     
   public class AsynchronousClient  
   {  
       // The port number for the remote device.    
       private const int port = 443;  
     
       // ManualResetEvent instances signal completion.    
       private static ManualResetEvent connectDone =  
           new ManualResetEvent(false);  
       private static ManualResetEvent sendDone =  
           new ManualResetEvent(false);  
       private static ManualResetEvent receiveDone =  
           new ManualResetEvent(false);  
     
       // The response from the remote device.    
       private static String response = String.Empty;  
     
       private static void StartClient()  
       {  
           // Connect to a remote device.    
           try  
           {  
               // Establish the remote endpoint for the socket.    
               // The name of the  
               // remote device is "host.contoso.com".    
               IPHostEntry ipHostInfo = Dns.GetHostEntry("networks.net");  
               IPAddress ipAddress = ipHostInfo.AddressList[0];  
               IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);  
     
               // Create a TCP/IP socket.    
               Socket client = new Socket(ipAddress.AddressFamily,  
                   SocketType.Stream, ProtocolType.Tcp);  
     
               // Connect to the remote endpoint.    
               client.BeginConnect(remoteEP,  
                   new AsyncCallback(ConnectCallback), client);  
               connectDone.WaitOne();  
     
               // Send test data to the remote device.    
               Send(client, "deneme fkfglb <EOF>");  
               sendDone.WaitOne();  
     
               // Receive the response from the remote device.    
               Receive(client);  
               receiveDone.WaitOne();  
     
               // Write the response to the console.    
               Console.WriteLine("Response received : {0}", response);  
     
               // Release the socket.    
               client.Shutdown(SocketShutdown.Both);  
               client.Close();  
     
           }  
           catch (Exception e)  
           {  
               Console.WriteLine(e.ToString());  
           }  
       }  
     
       private static void ConnectCallback(IAsyncResult ar)  
       {  
           try  
           {  
               // Retrieve the socket from the state object.    
               Socket client = (Socket)ar.AsyncState;  
     
               // Complete the connection.    
               client.EndConnect(ar);  
     
               Console.WriteLine("Socket connected to {0}",  
                   client.RemoteEndPoint.ToString());  
     
               // Signal that the connection has been made.    
               connectDone.Set();  
           }  
           catch (Exception e)  
           {  
               Console.WriteLine(e.ToString());  
           }  
       }  
     
       private static void Receive(Socket client)  
       {  
           try  
           {  
               // Create the state object.    
               StateObject state = new StateObject();  
               state.workSocket = client;  
     
               // Begin receiving the data from the remote device.    
               client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,  
                   new AsyncCallback(ReceiveCallback), state);  
           }  
           catch (Exception e)  
           {  
               Console.WriteLine(e.ToString());  
           }  
       }  
     
       private static void ReceiveCallback(IAsyncResult ar)  
       {  
           try  
           {  
               // Retrieve the state object and the client socket  
               // from the asynchronous state object.    
               StateObject state = (StateObject)ar.AsyncState;  
               Socket client = state.workSocket;  
     
               // Read data from the remote device.    
               int bytesRead = client.EndReceive(ar);  
     
               if (bytesRead > 0)  
               {  
                   // There might be more data, so store the data received so far.    
                   state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));  
     
                   // Get the rest of the data.    
                   client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,  
                       new AsyncCallback(ReceiveCallback), state);  
               }  
               else  
               {  
                   // All the data has arrived; put it in response.    
                   if (state.sb.Length > 1)  
                   {  
                       response = state.sb.ToString();  
                   }  
                   // Signal that all bytes have been received.    
                   receiveDone.Set();  
               }  
           }  
           catch (Exception e)  
           {  
               Console.WriteLine(e.ToString());  
           }  
       }  
     
       private static void Send(Socket client, String data)  
       {  
           // Convert the string data to byte data using ASCII encoding.    
           byte[] byteData = Encoding.ASCII.GetBytes(data);  
     
           // Begin sending the data to the remote device.    
           client.BeginSend(byteData, 0, byteData.Length, 0,  
               new AsyncCallback(SendCallback), client);  
       }  
     
       private static void SendCallback(IAsyncResult ar)  
       {  
           try  
           {  
               // Retrieve the socket from the state object.    
               Socket client = (Socket)ar.AsyncState;  
     
               // Complete sending the data to the remote device.    
               int bytesSent = client.EndSend(ar);  
               Console.WriteLine("Sent {0} bytes to server.", bytesSent);  
     
               // Signal that all bytes have been sent.    
               sendDone.Set();  
           }  
           catch (Exception e)  
           {  
               Console.WriteLine(e.ToString());  
           }  
       }  
     
       public static int Main(String[] args)  
       {  
           StartClient();  
           return 0;  
       }  
   }  
Microsoft System Center
Microsoft System Center
A suite of Microsoft systems management products that offer solutions for managing datacenter resources, private clouds, and client devices.
1,009 questions
Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
13,205 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,002 questions
{count} votes

Accepted answer
  1. Jose Zero 576 Reputation points
    2022-08-17T23:48:59.403+00:00

    There was lots of similar issues at old forums.asp.net with proper explanation :-(

    When connecting over HTTPS, you have to consider if target is using SSL, TLS 1.1 or TLS 1.2, and properly enable on your end.
    Also have in mind .NET will check for valid certificate of target address.

    I know you working on .Net Core6, but for .Net Framework whe use:
    To enable SSL, TLS 1.1 and TLS 1.2 on your end. Important this set is Global (for .Net Framework). This should fix exception "An existing connection was ..."
    System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol Or System.Net.SecurityProtocolType.Tls11 Or System.Net.SecurityProtocolType.Tls12

    system.net.servicepointmanager.securityprotocol

    Look for system.net.servicepointmanager.servercertificatevalidationcallback if you want bypass certificate validation.

    3 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Gary Reynolds 9,416 Reputation points
    2022-08-16T06:33:43.973+00:00

    Hi,

    The ping will confirm that ping and ICMP is working, it doesn't confirm that the server is listening on port 443.

    I'm not familiar with the .Net libraries, but how are you managing the SSL handshake, is there an option that you need to set or will it do the SSL connection transparently or do you need to use Secure Sockets Layer - https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-secure-sockets-layer

    Gary.

    1 person found this answer helpful.
    0 comments No comments

  2. Limitless Technology 44,376 Reputation points
    2022-08-17T15:11:24.5+00:00

    Hello

    Thank you for your question and reaching out. I can understand you are having issues related to making connection to remote host.

    This error usually indicates that the remote side of the connection has been closed (normally by sending a TCP/IP 'RST' packet). If you're using a third-party application, the following are the most likely causes:

    You are sending malformed data to the application (which could include sending an HTTPS request to an HTTP server)
    You caused the third-party application to crash by triggering a bug in it.

    For some reason, the network connectivity between the client and the server is failing.

    ---

    --If the reply is helpful, please Upvote and Accept as answer--

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.