设置套接字发送/接收超时小于500ms在.NET [英] Setting socket send/receive timeout to less than 500ms in .NET
问题描述
还有没有其他的方法来超时套接字接收操作,如果它,例如,需要更长的时间超过10ms才能完成?
答案很简单:你不知道。
发送()
和接收()
通话阻止程序的流程,直到数据被发送,接收或发生了错误。
如果你想有更多的控制你的电话,有几个可用的机制。最简单的方法是使用民意测验()
。
插座S;
// ...
//轮询套接字接收了10毫秒超时。
如果(s.Poll(10000,SelectMode.SelectRead))
{
s.Receive(); //此调用不会阻止
}
其他
{
// 时间到
}
您也可以使用选择()
, BeginReceive()
或 ReceiveAsync()
为其他类型的行为。
我建议你读Stevens的UNIX网络上的非阻塞套接字使用编程第6和第16进行更深入的信息。尽管这本书有UNIX的名称中,整体插座架构本质上是在UNIX和Windows(和.net)
相同According to MSDN documentation it is not possible to set Socket.SendTimeout to a value less than 500ms: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.sendtimeout Same rule is valid for Socket.ReceiveTimeout (even it is not mentioned in MSDN documentation, this is true, as both cases were tested practically).
Are there any other ways to timeout a socket receive operation if it, for example, takes longer than 10ms to complete?
The simple answer is "you don't".
Send()
and Receive()
calls block the flow of the program until data was sent, received or an error occurred.
If you want to have more control over your calls, there are several mechanisms available. The simplest is to use Poll()
.
Socket s;
// ...
// Poll the socket for reception with a 10 ms timeout.
if (s.Poll(10000, SelectMode.SelectRead))
{
s.Receive(); // This call will not block
}
else
{
// Timed out
}
You can also use Select()
, BeginReceive()
or ReceiveAsync()
for other types of behaviors.
I recommend you read Stevens' UNIX Network Programming chapters 6 and 16 for more in-depth information on non-blocking socket usage. Even though the book has UNIX in its name, the overall sockets architecture is essentially the same in UNIX and Windows (and .net)
这篇关于设置套接字发送/接收超时小于500ms在.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!