c#-.Net WebRequest超时与TCP超时
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-.Net WebRequest超时与TCP超时,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5040字,纯文字阅读大概需要8分钟。
内容图文
![c#-.Net WebRequest超时与TCP超时](/upload/InfoBanner/zyjiaocheng/662/8013d5dbe8a04c99881901ce80607f73.jpg)
题
如何为单个WebRequest配置TCP超时?
语境
根据文档,WebRequest.Timeout:
The length of time, in milliseconds, until the request times out, or
the value Timeout.Infinite to indicate that the request does not time
out. The default value is defined by the descendant class.
从不存在的终结点(IIS在请求的端口上没有服务绑定)请求Web资源失败,并且超时时间大约为21秒,并且保持不变.
根据此serverfault answer,这似乎是连接TCP超时.
样例代码
public static async Task<string> WebRequestToString(string requestUri, int timeoutMilliseconds)
{
var request = WebRequest.Create(requestUri) as HttpWebRequest;
request.KeepAlive = false;
request.Timeout = timeoutMilliseconds;
request.ReadWriteTimeout = timeoutMilliseconds;
using (var response = await request.GetResponseAsync() as HttpWebResponse)
{
// Get the response stream
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseBody = await reader.ReadToEndAsync();
return responseBody;
}
}
}
static void Main(string[] args)
{
string uri = "http://10.15.1.24:8081/thiservicedoesnotexist/";
int timeoutMilliseconds = 10;
Stopwatch sw = new Stopwatch();
sw.Start();
try
{
WebRequestToString(uri, timeoutMilliseconds).Wait();
}
catch (AggregateException ex)
{
Console.WriteLine(ex.ToString());
}
sw.Stop();
Console.WriteLine("Elaped {0}ms", sw.ElapsedMilliseconds);
Console.ReadKey();
}
示例输出
System.AggregateException: One or more errors occurred. ---> System.Net.WebExcep
tion: Unable to connect to the remote server ---> System.Net.Sockets.SocketExcep
tion: A connection attempt failed because the connected party did not properly r
espond after a period of time, or established connection failed because connecte
d host has failed to respond 10.15.1.24:8081
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Sock
et s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state,
IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TimeoutTests.Program.<WebRequestToString>d__0.MoveNext() in \\vmware-host\
shared folders\Documents\Visual Studio 2012\Projects\TimeoutTests\TimeoutTests\P
rogram.cs:line 20
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceled
Exceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationTo
ken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at TimeoutTests.Program.Main(String[] args) in \\vmware-host\shared folders\D
ocuments\Visual Studio 2012\Projects\TimeoutTests\TimeoutTests\Program.cs:line 4
0
---> (Inner Exception #0) System.Net.WebException: Unable to connect to the remo
te server ---> System.Net.Sockets.SocketException: A connection attempt failed b
ecause the connected party did not properly respond after a period of time, or e
stablished connection failed because connected host has failed to respond 10.15.
1.24:8081
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Sock
et s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state,
IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,
Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchron
ization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TimeoutTests.Program.<WebRequestToString>d__0.MoveNext() in \\vmware-host\
shared folders\Documents\Visual Studio 2012\Projects\TimeoutTests\TimeoutTests\P
rogram.cs:line 20<---
Elaped 21169ms
解决方法:
我非常怀疑此超时实际上与TCP连接超时相同.
webrequest超时的文档如下:
直到请求超时的时间长度(以毫秒为单位),或者值Timeout.Infinite,指示请求没有超时.默认值由后代类定义.
这是您的请求(即HTTP)级别的超时.可能是与服务器的连接已建立,但创建响应需要很长时间.同样,时间可能会超时.
webrequest如何处理此问题并将其映射到TCP取决于实现.
建立连接的TCP超时不能无限.
我还阅读以下内容:
Timeout属性指示直到请求超时并引发WebException为止的时间长度(以毫秒为单位). Timeout属性仅影响使用GetResponse方法发出的同步请求.要使异步请求超时,请使用Abort方法.
您是异步的!
内容总结
以上是互联网集市为您收集整理的c#-.Net WebRequest超时与TCP超时全部内容,希望文章能够帮你解决c#-.Net WebRequest超时与TCP超时所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。