设置底层套接字ReceiveTimeout
属性就可以了。您可以像这样访问它:yourTcpClient.Client.ReceiveTimeout
。您可以阅读文档以获取更多信息。
现在,只要某些数据到达套接字,该代码将仅“hibernate”,否则,如果在读取操作开始时超过20ms,如果没有数据到达,它将引发异常。如果需要,我可以调整此超时时间。现在,我不必为每次迭代付出20毫秒的代价,而只是在最后一次读取操作时才付出代价。因为我在从服务器读取的第一个字节中具有消息的内容长度,所以我可以使用它来进一步调整它,并且如果已经收到所有期望的数据,则不尝试读取。
我发现使用ReceiveTimeout比实现异步读取要容易得多…这是工作代码:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}