无法从传输连接读取数据:现有连接被远程主机强制关闭

发布于 2024-10-26 22:04:43 字数 454 浏览 1 评论 0原文

我有一个服务器应用程序,有时,当客户端尝试连接时,我会收到以下错误:

在此处输入图像描述

< em>注意:“无法从客户端获取流或登录失败”是我在 catch 语句中添加的文本

,它停止的行( sThread :第 96 行)是:

tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
sr = new StreamReader(clientStream);
sw = new StreamWriter(clientStream);

// line 96:                 
a = sr.ReadLine();

可能导致的原因这个问题?请注意,它不会一直发生

I have a server app and sometimes, when the client tries to connect, I get the following error:

enter image description here

NOTE: the "couldn't get stream from client or login failed" is a text that's added by me in catch statement

and the line at which it stops ( sThread : line 96 ) is :

tcpClient = (TcpClient)client;
clientStream = tcpClient.GetStream();
sr = new StreamReader(clientStream);
sw = new StreamWriter(clientStream);

// line 96:                 
a = sr.ReadLine();

What may be causing this problem? Note that it doesn't happen all the time

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

撑一把青伞 2024-11-02 22:04:43

我在调用网络服务时收到此错误。该问题还与传输级安全有关。我可以通过网站项目调用 Web 服务,但是当在测试项目中重用相同的代码时,我会收到包含此消息的 WebException。在调用之前添加以下行解决了该问题:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

编辑

System.Net.ServicePointManager.SecurityProtocol - 此属性
选择安全套接字层 (SSL) 或传输的版本
用于使用以下协议的新连接的层安全 (TLS) 协议
仅安全超文本传输​​协议 (HTTPS) 方案;现存的
连接没有改变。

我相信在 TLS 握手期间选择协议版本时,SecurityProtocol 配置非常重要。

TLS 握手 - 此协议用于交换双方通过 TLS 交换实际应用数据所需的所有信息。

ClientHello - 客户端发送一条 ClientHello 消息,指定其支持的最高 TLS 协议版本...

ServerHello - 服务器响应 ServerHello 消息,其中包含所选的协议版本...所选的协议版本应该是客户端和服务器都支持的最高版本。例如,如果客户端支持TLS版本1.1,服务器支持版本1.2,则应选择版本1.1;不应选择 1.2 版本。

I received this error when calling a web-service. The issue was also related to transport level security. I could call the web-service through a website project, but when reusing the same code in a test project I would get a WebException that contained this message. Adding the following line before making the call resolved the issue:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Edit

System.Net.ServicePointManager.SecurityProtocol - This property
selects the version of the Secure Sockets Layer (SSL) or Transport
Layer Security (TLS) protocol to use for new connections that use the
Secure Hypertext Transfer Protocol (HTTPS) scheme only; existing
connections are not changed.

I believe the SecurityProtocol configuration is important during the TLS handshake when selecting the protocol version.

TLS handshake - This protocol is used to exchange all the information required by both sides for the exchange of the actual application data by TLS.

ClientHello - A client sends a ClientHello message specifying the highest TLS protocol version it supports ...

ServerHello - The server responds with a ServerHello message, containing the chosen protocol version ... The chosen protocol version should be the highest that both the client and server support. For example, if the client supports TLS version 1.1 and the server supports version 1.2, version 1.1 should be selected; version 1.2 should not be selected.

压抑⊿情绪 2024-11-02 22:04:43

此错误通常意味着目标计算机正在运行,但您尝试连接的服务不可用。 (它停止、崩溃或正忙于另一个请求。)

英语:
已建立与计算机(运行服务的远程主机/服务器/PC)的连接,但由于该服务在该计算机上不可用,因此该计算机无法连接知道如何处理该请求。

如果与计算机的连接不可用,您会看到不同的错误。我忘记了它是什么,但它的意思是“服务无法访问”或“不可用”。

编辑 - 添加

这可能是由防火墙阻止端口引起的,但考虑到您说它是间歇性的(“有时当客户端尝试连接时”),这不太可能。我最初没有包含这一点,因为在回复之前我已经在心里排除了这一点。

This error usually means that the target machine is running, but the service that you're trying to connect to is not available. (Either it stopped, crashed, or is busy with another request.)

In English:
The connection to the machine (remote host/server/PC that the service runs at) was made but since the service was not available on that machine, the machine didn't know what to do with the request.

If the connection to the machine was not available, you'd see a different error. I forget what it is, but it's along the lines of "Service Unreachable" or "Unavailable".

Edit - added

It IS possible that this is being caused by a firewall blocking the port, but given that you say it's intermittent ("sometimes when the client tries to connect"), that's very unlikely. I didn't include that originally because I had ruled it out mentally before replying.

在你怀里撒娇 2024-11-02 22:04:43

我的具体案例场景是 Azure 应用服务将最低 TLS 版本更改为 1.2,

我不知道从现在开始这是否是默认版本,但将其更改回 1.0 使其可以正常工作。

您可以访问“SSL 设置”中的设置。

My specific case scenario was that the Azure app service had the minimum TLS version changed to 1.2

I don't know if that's the default from now on, but changing it back to 1.0 made it work.

You can access the setting inside "SSL Settings".

放赐 2024-11-02 22:04:43

据“汉斯·沃恩”回复。

在进行调用之前添加以下行解决了问题:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

添加安全协议并工作正常后,但我必须在每个不健康的 API 调用之前添加。我只是将 .net 框架版本至少升级到 4.6,并且按预期工作不需要在每次 API 调用之前添加。

According to "Hans Vonn" replies.

Adding the following line before making the call resolved the issue:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

After adding Security protocol and working fine but I have to add before every API call which is not healthy. I just upgrade .net framework version at least 4.6 and working as expected do not require to adding before every API call.

坏尐絯 2024-11-02 22:04:43

不确定这些博客文章中的哪些修复有帮助,但其中一个为我解决了这个问题...

http://briancaos.wordpress.com/2012/07/06/unable-to-read-data- from-the-transport-connection-the-connection-was-close/

对我有帮助的技巧是停止使用 WebRequest 并使用 HttpWebRequest 代替。 HttpWebRequest 允许我使用 3 个重要设置:

http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcously-filled-by-the-remote-host/

  • 第 1 步:禁用 KeepAlive
  • 第 2 步:将 ProtocolVersion 设置为 Version10
  • 第 3 步:限制服务点数量

Not sure which of the fixes in these blog posts helped, but one of them sorted this issue for me ...

http://briancaos.wordpress.com/2012/07/06/unable-to-read-data-from-the-transport-connection-the-connection-was-closed/

The trick that helped me was to quit using a WebRequest and use a HttpWebRequest instead. The HttpWebRequest allows me to play with 3 important settings:

and

http://briancaos.wordpress.com/2012/06/15/an-existing-connection-was-forcibly-closed-by-the-remote-host/

  • STEP 1: Disable KeepAlive
  • STEP 2: Set ProtocolVersion to Version10
  • STEP 3: Limiting the number of service points
锦爱 2024-11-02 22:04:43

对于那些稍后可能会发现这一点的人,在 .NET 版本 4.6 之后,我也遇到了这个问题。

确保检查 web.config 文件中的以下行:

<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5" />

如果您在服务器上运行 4.6.x 或更高版本的 .NET,请确保调整这些 targetFramework 值以匹配服务器上框架的版本。如果您的版本读取低于 4.6.x,那么我建议您升级 .NET 并使用较新的版本,除非您的代码依赖于旧版本(在这种情况下,您应该考虑更新它)。

我将 targetFrameworks 更改为 4.7.2,问题消失了:

<compilation debug="true" targetFramework="4.7.2">
...
<httpRuntime targetFramework="4.7.2" />

较新的框架通过使用可用的最佳协议并阻止不安全或过时的协议来解决此问题。如果您尝试连接或调用的远程服务出现此错误,则可能是它们不再支持旧协议。

For those who may find this later, after .NET version 4.6, I was running into this problem as well.

Make sure that you check your web.config file for the following lines:

<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5" />

If you are running 4.6.x or a higher version of .NET on the server, make sure you adjust these targetFramework values to match the version of the framework on your server. If your versions read less than 4.6.x, then I would recommend you upgrade .NET and use the newer version unless your code is dependent on an older version (which, in that case, you should consider updating it).

I changed the targetFrameworks to 4.7.2 and the problem disappeared:

<compilation debug="true" targetFramework="4.7.2">
...
<httpRuntime targetFramework="4.7.2" />

The newer frameworks sort this issue out by using the best protocol available and blocking insecure or obsolete ones. If the remote service you are trying to connect to or call is giving this error, it could be that they don't support the old protocols anymore.

怎樣才叫好 2024-11-02 22:04:43

从我们的一台服务器调用 HTTPS 服务也会引发“无法从传输连接读取数据:现有连接被强制关闭”异常。不过,HTTP 服务运行良好。用Wireshark查看是TLS握手失败。最终服务器上的密码套件需要更新。

Calls to HTTPS services from one of our servers were also throwing the "Unable to read data from the transport connection : An existing connection was forcibly closed" exception. HTTP service, though, worked fine. Used Wireshark to see that it was a TLS handshake Failure. Ended up being that the cipher suite on the server needed to be updated.

姜生凉生 2024-11-02 22:04:43

这解决了我的问题。我在发出请求之前添加了这一行:

System.Net.ServicePointManager.Expect100Continue = false;

似乎服务器中存在不支持 100 继续行为的代理。

This solved my problem. I added this line before the request is made:

System.Net.ServicePointManager.Expect100Continue = false;

It seemed there were a proxy in the way of the server that not supported 100-continue behavior.

安静被遗忘 2024-11-02 22:04:43

这对解决间歇性问题没有帮助,但可能对其他有类似问题的人有用。

我克隆了一个虚拟机,并使用新的 IP 地址在不同的网络上启动它,但没有更改 IIS 中的绑定。 Fiddler 向我显示“无法从传输连接读取数据:现有连接被远程主机强制关闭”,IE 告诉我“在高级设置中打开 TLS 1.0、TLS 1.1 和 TLS 1.2”。更改与新 IP 地址的绑定为我解决了这个问题。

This won't help for intermittent issues, but may be useful for other people with a similar problem.

I had cloned a VM and started it up on a different network with a new IP address but not changed the bindings in IIS. Fiddler was showing me "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host" and IE was telling me "Turn on TLS 1.0, TLS 1.1, and TLS 1.2 in Advanced settings". Changing the binding to the new IP address solved it for me.

又爬满兰若 2024-11-02 22:04:43

由于某种原因,与服务器的连接丢失了。可能是服务器显式关闭了连接,或者服务器上的错误导致连接意外关闭。或者客户端和服务器(交换机或路由器)之间的某些东西断开了连接。

可能是服务器代码导致了问题,也可能不是。如果您有权访问服务器代码,则可以在其中进行一些调试,以告诉您客户端连接何时关闭。这可能会给您一些有关连接何时以及为何被丢弃的指示。

在客户端,您必须编写代码以考虑到服务器随时出现故障的可能性。事情就是这样:网络连接本质上是不可靠的。

For some reason, the connection to the server was lost. It could be that the server explicitly closed the connection, or a bug on the server caused it to be closed unexpectedly. Or something between the client and the server (a switch or router) dropped the connection.

It might be server code that caused the problem, and it might not be. If you have access to the server code, you can put some debugging in there to tell you when client connections are closed. That might give you some indication of when and why connections are being dropped.

On the client, you have to write your code to take into account the possibility of the server failing at any time. That's just the way it is: network connections are inherently unreliable.

书间行客 2024-11-02 22:04:43
  • 我从控制台应用程序发送 HttpWebRequest,而 UserAgent 是
    null(默认),因此设置 UserAgent 与设置一起使用
    安全协议。
  • 应在创建 HttpWebRequest 之前设置 SecurityProtocol。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("yourpostURL");
req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36";
  • I was sending the HttpWebRequest from Console App, and UserAgent was
    null by (default), so setting UserAgent worked along with setting
    SecurityProtocol.
  • Should set SecurityProtocol before creating HttpWebRequest.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("yourpostURL");
req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36";
顾挽 2024-11-02 22:04:43

webrequest用户代理默认为空。只需谷歌“阻止空用户代理”,您就会发现许多网络服务器管理员强烈希望做到这一点。

发送我的请求
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0";
解决了这个问题。

The webrequest user agent is null by default. Just google "block empty user agent" and you'll find a strong desire of many web server admins to do just that.

Sending my request with
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0";
fixed the issue.

生活了然无味 2024-11-02 22:04:43

我在使用 adomd 对 Microsoft 分析服务运行 mdx 查询的 python clr 时遇到了错误,

我在 Hans Vonn 的帮助下解决了这个问题,这是 python 版本:

clr.AddReference("System.Net")
from System.Net import ServicePointManager, SecurityProtocolType 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls

I experienced the error with python clr running mdx query to Microsoft analytic services using adomd

I solved it with help of Hans Vonn and here is the python version:

clr.AddReference("System.Net")
from System.Net import ServicePointManager, SecurityProtocolType 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls
一袭白衣梦中忆 2024-11-02 22:04:43

我过去也遇到过这个问题。我正在使用PostgreSQL,当我运行我的程序时,有时它会连接,有时会抛出这样的错误。

当我试验我的代码时,我将连接代码放在公共表单下方的第一行。这是一个例子:

BEFORE:

    public Form1()
        {
        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!





        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());
        }

NOW:

    public Form1()
        {
        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());





        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!

        }

我认为程序在做任何事情之前必须首先读取连接,我不知道,如果我错了,请纠正我。但根据我的研究,这不是代码问题——实际上是机器本身的问题。

I get that problem in the past. I'm using PostgreSQL and when I run my program, sometimes it connects and sometimes it throws an error like that.

When I experiment with my code, I put my Connection code at the very first line below the public Form. Here is an example:

BEFORE:

    public Form1()
        {
        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!





        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());
        }

NOW:

    public Form1()
        {
        //Connect to Database to generate auto number
        NpgsqlConnection iConnect = new NpgsqlConnection("Server=localhost;Port=5432;User ID=postgres;Password=pass;Database=DB");
        iConnect.Open();
        NpgsqlCommand iQuery = new NpgsqlCommand("Select * from table1", iConnect);
        NpgsqlDataReader iRead = iQuery.ExecuteReader();
        NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(iQuery);

        DataSet iDataSet = new DataSet();
        iAdapter.Fill(iDataSet, "ID");

        MessageBox.Show(iDataSet.Tables["ID"].Rows.Count.ToString());





        //HERE LIES SOME CODES FOR RESIZING MY CONTROLS DURING RUNTIME
        //CODE
        //CODE AGAIN
        //ANOTHER CODE
        //CODE NA NAMAN
        //CODE PA RIN!

        }

I think that the program must read first the connection before doing anything, I don't know, correct me if I'm wrong. But according to my research, it's not a code problem - it was actually from the machine itself.

没有心的人 2024-11-02 22:04:43
System.Net.ServicePointManager.Expect100Continue = false;

有时,由于 Web 服务器上实施的代理服务器的原因,会出现此问题。通过在调用发送服务之前放置此行来绕过代理服务器。

System.Net.ServicePointManager.Expect100Continue = false;

This issue sometime occurs due the reason of proxy server implemented on web server. To bypass the proxy server by putting this line before calling the send service.

你又不是我 2024-11-02 22:04:43

我们遇到了一个非常相似的问题,客户的网站尝试连接到我们的 Web API 服务并获取相同的消息。当运行 IIS 的服务器上没有代码更改或 Windows 更新时,这种情况完全突然发生。

在我们的案例中,调用网站使用的 .Net 版本仅支持 TLS 1.0,并且由于某种原因,运行 IIS 的服务器似乎已停止接受 TLS 1.0 调用。为了诊断我们必须通过 IIS 服务器上的注册表显式启用 TLS,然后重新启动该服务器。这些是注册表键:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:


    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

我对这里的另一个问题的回答有我们用来添加条目的powershell脚本:

注意:启用旧的安全协议不是一个好主意,在我们的案例中,正确的答案是让客户端网站更新其代码以使用 TLS 1.2,但上面的注册表项可以帮助诊断问题首位。

We had a very similar issue whereby a client's website was trying to connect to our Web API service and getting that same message. This started happening completely out of the blue when there had been no code changes or Windows updates on the server where IIS was running.

In our case it turned out that the calling website was using a version of .Net that only supported TLS 1.0 and for some reason the server where our IIS was running stopped appeared to have stopped accepting TLS 1.0 calls. To diagnose that we had to explicitly enable TLS via the registry on the IIS's server and then restart that server. These are the reg keys:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.1\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
    1.2\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

If that doesn't do it, you could also experiment with adding the entry for SSL 2.0:


    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
    "DisabledByDefault"=dword:00000000
    "Enabled"=dword:00000001

My answer to another question here has this powershell script that we used to add the entries:

NOTE: Enabling old security protocols is not a good idea, the right answer in our case was to get the client website to update it's code to use TLS 1.2, but the registry entries above can help diagnose the issue in the first place.

岁吢 2024-11-02 22:04:43

发生这种情况的原因是我对 DI 提供商有递归依赖。就我而言,我有:

services.AddScoped(provider => new CfDbContext(builder.Options));
services.AddScoped(provider => provider.GetService<CfDbContext>());

修复是删除第二个范围服务注册

services.AddScoped(provider => new CfDbContext(builder.Options));

The reason this was happening to me was I had a recursive dependency in my DI provider. In my case I had:

services.AddScoped(provider => new CfDbContext(builder.Options));
services.AddScoped(provider => provider.GetService<CfDbContext>());

Fix was to just remove the second scoped service registration

services.AddScoped(provider => new CfDbContext(builder.Options));
木有鱼丸 2024-11-02 22:04:43

遇到了类似的问题,并且根据我使用的应用程序以及我们是否绕过防火墙/负载均衡器而出现以下错误:

与 [blah](针对 #136)的 HTTPS 握手失败。
System.IO.IOException 无法从传输读取数据
连接:现有连接被远程强制关闭
主机

ReadResponse() 失败:服务器未返回此请求的完整响应。服务器返回 0 字节。

事实证明,问题是 SSL 服务器证书丢失并且未安装在几台服务器上。

Had a similar problem and was getting the following errors depending on what app I used and if we bypassed the firewall / load balancer or not:

HTTPS handshake to [blah] (for #136) failed.
System.IO.IOException Unable to read data from the transport
connection: An existing connection was forcibly closed by the remote
host

and

ReadResponse() failed: The server did not return a complete response for this request. Server returned 0 bytes.

The problem turned out to be that the SSL Server Certificate got missed and wasn't installed on a couple servers.

弃爱 2024-11-02 22:04:43

对我来说,这是一个问题,在 IIS 绑定中它具有 Web 服务器的 IP 地址。
我将其更改为使用所有未分配的 IP,并且我的应用程序开始工作。

For me, It was an issue where in the IIS binding it had the IP address of the web server.
I changed it to use all unassigned IPs and my application started to work.

£烟消云散 2024-11-02 22:04:43

我收到此错误只是因为我尝试与纯 https 服务器建立 http 连接。将 URI 中的请求协议从 http 更改为 https 即可解决该问题。

I received this error simply because I was attempting to make an http connection to an https-only server. Changing the request protocol in the URI from http to https thus resolved it.

千年*琉璃梦 2024-11-02 22:04:43

这就是我解决问题的方法:

                int i = 0;
                while (stream.DataAvailable == true)
                {
                    bytes[i] = ((byte)stream.ReadByte());
                    i++;
                }

                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0}", data);

This is how I solved the issue:

                int i = 0;
                while (stream.DataAvailable == true)
                {
                    bytes[i] = ((byte)stream.ReadByte());
                    i++;
                }

                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: {0}", data);
不疑不惑不回忆 2024-11-02 22:04:43

我运行了一个第三方应用程序(Fiddler)来尝试查看正在发送的请求。关闭此应用程序为我解决了这个问题

I had a Third Party application (Fiddler) running to try and see the requests being sent. Closing this application fixed it for me

潇烟暮雨 2024-11-02 22:04:43

如果您在域上有 https 证书,请确保您在 IIS 中具有与域名的 https 绑定。
在IIS中->选择您的域名 ->单击绑定
站点绑定窗口打开。添加 https 的绑定。

If you have a https certificate on the domain, make sure you have the https binding to the domain name in IIS.
In IIS -> Select your domain -> Click on Bindings
Site Bindings Window opens up. Add a binding for https.

飘过的浮云 2024-11-02 22:04:43

首先尝试检查是否可以建立握手。我之前在上传文件时遇到过这个问题,当我删除上传并检查给定参数是否可以登录时,我才发现问题是不存在的路由。

Try checking if you can establish handshake in the first place. I had this issue before when uploading a file and I only figured out that the issue was the nonexistent route when I removed the upload and checked if it can login given the parameters.

断肠人 2024-11-02 22:04:43

另一种选择是检查使用 try-catch 块生成的错误代码并首先捕获 WebException。

就我而言,错误代码是“SendFailure”,因为 HTTPS url 上的证书问题,一旦我点击 HTTP,问题就得到了解决。

https:// learn.microsoft.com/en-us/dotnet/api/system.net.webexceptionstatus?redirectedfrom=MSDN&view=netframework-4.8

Another option would be to check the error code generated using try-catch block and first catching a WebException.

In my case, the error code was "SendFailure" because of certificate issue on HTTPS url, once I hit HTTP, that got resolved.

https://learn.microsoft.com/en-us/dotnet/api/system.net.webexceptionstatus?redirectedfrom=MSDN&view=netframework-4.8

隔岸观火 2024-11-02 22:04:43

当代理服务器内的服务不可用时会出现此问题。我们可以绕过代理服务器。
在启动服务之前,应用此代码行。

System.Net.ServicePointManager.Expect100Continue = false;

更多详细信息

This problem occurring when the Service is Unavailable within the proxy server. We can bypass the proxy server.
Before start, the service, apply this code line.

System.Net.ServicePointManager.Expect100Continue = false;

Further details

雪若未夕 2024-11-02 22:04:43

应考虑侦听器缓冲区大小不足的情况。长度超过缓冲区大小的消息也会触发 OP 异常

在以下示例中,如果我们将 ma​​xBufferSize1024 减少到 10 并发送一条 ma​​xBufferSize 消息strong>11 字节,我们还会得到无法从传输连接读取数据:引发远程主机强行关闭现有连接异常。

internal class MyTcpListener
{
    static void Main(string[] args)
    {

        // Set the TcpListener on port 13000.
        IPAddress serverAddress = IPAddress.Parse("127.0.0.1");
        int serverPort = 13000;
        int maxBufferSize = 1024;

        launchTcpListener(serverAddress, serverPort, maxBufferSize);

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();

    }

    // https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=net-7.0
    private static void launchTcpListener(IPAddress serverAddress, int serverPort, int maxBufferSize)
    {
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        TcpListener server = null;

        try
        {

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(serverAddress, serverPort);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[maxBufferSize];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.WriteLine("Listening at {0}:{1}", serverAddress, serverPort);

                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                using (TcpClient client = server.AcceptTcpClient())
                {

                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int receivedBytes;

                    // Loop to receive all the data sent by the client.
                    while ((receivedBytes = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {

                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, receivedBytes);

                        string currentTime = DateTime.Now.ToString();
                        Console.WriteLine("At {0} received: {1}", currentTime, data);

                        // Processamento de dados


                        // Embora seja facultativo, mas deve enviar-se feedback quanto à validade dos pedidos
                        // Nesta amostra isto a devolver os dados recebidos
                        byte[] responseData = System.Text.Encoding.UTF8.GetBytes(data);
                        stream.Write(responseData, 0, responseData.Length);
                        Console.WriteLine("Server response: {0}", data);
                    }

                }

            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server?.Stop();
        }
    }
}

Insufficient listener buffer size should be taken into consideration. Messages longer than buffer size also triggers OP excetion

On the following sample, if we reduce maxBufferSize from 1024 to just 10 and send a message of 11 bytes, we also get Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host is raised exception.

internal class MyTcpListener
{
    static void Main(string[] args)
    {

        // Set the TcpListener on port 13000.
        IPAddress serverAddress = IPAddress.Parse("127.0.0.1");
        int serverPort = 13000;
        int maxBufferSize = 1024;

        launchTcpListener(serverAddress, serverPort, maxBufferSize);

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();

    }

    // https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=net-7.0
    private static void launchTcpListener(IPAddress serverAddress, int serverPort, int maxBufferSize)
    {
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

        TcpListener server = null;

        try
        {

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(serverAddress, serverPort);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[maxBufferSize];
            String data = null;

            // Enter the listening loop.
            while (true)
            {
                Console.WriteLine("Listening at {0}:{1}", serverAddress, serverPort);

                // Perform a blocking call to accept requests.
                // You could also use server.AcceptSocket() here.
                using (TcpClient client = server.AcceptTcpClient())
                {

                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int receivedBytes;

                    // Loop to receive all the data sent by the client.
                    while ((receivedBytes = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {

                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.UTF8.GetString(bytes, 0, receivedBytes);

                        string currentTime = DateTime.Now.ToString();
                        Console.WriteLine("At {0} received: {1}", currentTime, data);

                        // Processamento de dados


                        // Embora seja facultativo, mas deve enviar-se feedback quanto à validade dos pedidos
                        // Nesta amostra isto a devolver os dados recebidos
                        byte[] responseData = System.Text.Encoding.UTF8.GetBytes(data);
                        stream.Write(responseData, 0, responseData.Length);
                        Console.WriteLine("Server response: {0}", data);
                    }

                }

            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            server?.Stop();
        }
    }
}
东北女汉子 2024-11-02 22:04:43

我想补充一点,我必须明确确保在调用 HttpClient PostAsync 之前指定 Ssl3 和其他内容。

将客户端代码升级到 .NET Framework 4.8 后会发生这种情况。也仅发生在特定的客户端工作站上。之前是在 4.6 上(这很令人困惑,因为其他人认为问题是从 4.​​6 开始的)。

using (var client = new HttpClient())
{
  System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3; 
  var response = client.PostAsync(new Uri(baseUri, "Token"), content).Result;
  // If no Ssl3 the above throws: "Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host"
  ...

Wanted to add that for me, I had to explicitly ensure Ssl3 plus others were specified just before the HttpClient PostAsync was called.

This occurred after upgrading the client code to .NET Framework 4.8. Only happened on a specific client workstation too. Previously it was on 4.6 (which was confusing as others suggested that the problems started at 4.6).

using (var client = new HttpClient())
{
  System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3; 
  var response = client.PostAsync(new Uri(baseUri, "Token"), content).Result;
  // If no Ssl3 the above throws: "Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host"
  ...
网白 2024-11-02 22:04:43

如果您使用的是 netframework 3.5,并通过 https 调用 Web API,则应使用 ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); 启用 TLS 1.1 和 1.2 以避免此问题:

        public string SendGetRequest(string url)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
        }

If you're using netframework 3.5, and call web API with https, you should use ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); to enable TLS 1.1 and 1.2 to avoid this issue:

        public string SendGetRequest(string url)
        {
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
        }

就我而言,我通过在应用程序中设置正确的 API 网址解决了此问题。

这是应用程序和 API 之间的错误连接。

In my case I resolved this problem setting a correct API's url in my application.

It was an error connection between the application and API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文