Why does HttpWebRequest not sent TCP Keep-Alive packages even when using ServicePointManager.SetTcpKeepAlive

你。 提交于 2021-02-07 08:11:37

问题


I want to retrieve some data with an HttpWebRequest (GET):

var request = (HttpWebRequest)WebRequest.Create(myUri);
request.Timeout = 5 * 60 * 1000;
request.ReadWriteTimeout = 5 * 60 * 1000;

// request.ServicePoint.SetTcpKeepAlive(true, 5 * 1000, 1000);
var response = request.GetResponse();

Unfortunately the computation on the server can take two or more minutes. So between me sending the header and finally receiving the data in the response stream the socket connection is idle.

With curl or a browser the response finally comes through. But when using HttpWebRequest I always get an exception after 90 seconds:

System.AggregateException: One or more errors occurred. --->
System.Net.WebException: Error getting response stream (ReadDone1): ReceiveFailure ---> 
System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. --->
System.Net.Sockets.SocketException: Connection reset by peer

When comparing the TCP traffic in Wireshark between curl and HttpWebRequest I noticed that curl sends TCP Keep-Alive packages (ACK). Unfortunately even after enabling

ServicePointManager.SetTcpKeepAlive(true, 5 * 1000, 1000);

before creating the HttpWebRequest I can't see the Keep-Alive packages in the Wireshark trace. Why does the underlying socket not send an ACK package every five seconds (I picked this short interval for debugging. In production it could be set one minute).

When I start curl with the --no-keepalive parameter it shows the same behavior (connection drop after 90s). Some network related stuff seems to disconnect the socket if there is no traffic.

Remark: I know the server should not do such lengthly computation in response to GET and hopefully the API will change in the future. It's just bugging me that I can not produce TCP Keep-Alive packages with .Net

来源:https://stackoverflow.com/questions/49092865/why-does-httpwebrequest-not-sent-tcp-keep-alive-packages-even-when-using-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!