An existing connection was forcibly closed by the remote host

[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
   System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6416371
   System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +130

 

An existing connection was forcibly closed by the remote host

Line 60: request.ContentLength = data.Length;
Line 61:
Line 62: using (var stream = request.GetRequestStream())
Line 63: {
Line 64: stream.Write(data, 0, data.Length);

 

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?

Solution :

we troubleshooted a “An existing connection was forcibly closed by the remote host:” error message. We made some basic tests, such as a “browser test” and found that the certificate used was not valid. However fixing the certificate did not solve the issue and we still see the same error message telling us that the existing connection is forcibly closed by the remote host when we run our ASP.NET application which makes an HTTP web request to https://test.com/ URL.

when this error come we need to to enable tls in our operating sysytem like below :

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols

TLS registry_details

Also need to add tls enable code in below solution

System.Net.ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“https://www.example.com/query“);
request.Method = “POST“;
request.ContentType = “application/json“;
string jsonOrder = JsonConvert.SerializeObject(hm);
var data = Encoding.UTF8.GetBytes(jsonOrder);
request.ContentLength = data.Length;using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
if (((HttpWebResponse)response).StatusDescription == “OK“)
{
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
responseMessage = reader.ReadToEnd();}
}

 

Also Learn More Tutorial :

Leave a Reply

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