gpt4 book ai didi

c# - 处理阻塞 .NET 套接字的超时

转载 作者:行者123 更新时间:2023-11-30 17:21:19 25 4
gpt4 key购买 nike

使用 Accept 方法创建的 TcpClient 实例用于管理客户端连接。当我需要终止服务器线程时出现问题,因为它在接收调用时被阻塞。

所以我设置了 TcpClient ReceiveTimeout,以便每 n 毫秒循环一次以测试退出条件。结果是 Receive 操作引发异常 (SocketException),错误代码为 SocketError.TimedOut。很好,我在想...

问题是属性Socket.Connected返回 false,但如 MSDN 文档中所述:

The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

所以,我按照说明去做:

try {
// Receive operation on socket stream
// Send operation on socket stream
} catch (SocketException e) {
if (e.SocketErrorCode == SocketError.TimedOut) {
try {
IAsyncResult asyncResult;
int sResult;

asyncResult = mSocket.Client.BeginSend(new byte[] {}, 0, 0, SocketFlags.None, delegate(IAsyncResult result) { }, null);
sResult = mSocket.Client.EndSend(asyncResult);
Debug.Assert(asyncResult.IsCompleted == true);

if (mSocket.Connected == false)
throw new Exception("not more connected"); // Always thrown
} catch (Exception e) {
// ...
}
}

但是,即使执行了 ynch Send 操作,mSocket.Connected 属性始终为 false,导致外层循环终止(其他线程调用 Disconnect 方法终止服务器线程)。

我错过了什么?

最佳答案

问题是如果发生超时,TcpClient 会断开连接。所以你的方法是行不通的。使用异步读/写函数或使用选择。

异步函数调用最简单的方法可能是这样的:

byte[] data = new byte[4096];
IASyncResult result = stream.BeginRead(data, 0, data.Length, null, null);
result.AsyncWaitHandle.WaitOne(<timeout value in ms>);
int bytes = stream.EndRead(result);

if (!result.IsCompleted)
<timed out>
else
<read data>
...

关于c# - 处理阻塞 .NET 套接字的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3574969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com