ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-12-09 06:06:22  阅读:336  来源: 互联网

标签:sockets networking c


使用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) {
             // ...
        }
}

但是,即使执行了aynch 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>
...

标签:sockets,networking,c
来源: https://codeday.me/bug/20191209/2097006.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有