.net - 如何处理异步套接字中的超时?

标签 .net sockets asynchronous asyncsocket

我有一个代码,它使用异步套接字向客户端发送消息并期待它的响应。如果客户端没有在指定的内部回复,它将认为超时。网上有些文章建议使用WaitOne,但这会阻塞线程,推迟使用I/O完成的目的。

在异步套接字中处理超时的最佳方法是什么?

 Sub OnSend(ByVal ar As IAsyncResult)
       Dim socket As Socket = CType(ar.AsyncState ,Socket)
       socket.EndSend(ar)

       socket.BeginReceive(Me.ReceiveBuffer, 0, Me.ReceiveBuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), socket)

 End Sub

最佳答案

您不能超时或取消异步 Socket操作。

你所能做的就是开始你自己的Timer关闭 Socket ——回调将立即被调用,EndX函数将返回 ObjectDisposedException如果你叫它。下面是一个例子:

using System;
using System.Threading;
using System.Net.Sockets;

class AsyncClass
{
     Socket sock;
     Timer timer;
     byte[] buffer;
     int timeoutflag;

     public AsyncClass()
     {
          sock = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

          buffer = new byte[256];
     }

     public void StartReceive()
     {
          IAsyncResult res = sock.BeginReceive(buffer, 0, buffer.Length,
                SocketFlags.None, OnReceive, null);

          if(!res.IsCompleted)
          {
                timer = new Timer(OnTimer, null, 1000, Timeout.Infinite);
          }
     }

     void OnReceive(IAsyncResult res)
     {
          if(Interlocked.CompareExchange(ref timeoutflag, 1, 0) != 0)
          {
                // the flag was set elsewhere, so return immediately.
                return;
          }

          // we set the flag to 1, indicating it was completed.

          if(timer != null)
          {
                // stop the timer from firing.
                timer.Dispose();
          }

          // process the read.

          int len = sock.EndReceive(res);
     }

     void OnTimer(object obj)
     {
          if(Interlocked.CompareExchange(ref timeoutflag, 2, 0) != 0)
          {
                // the flag was set elsewhere, so return immediately.
                return;
          }

          // we set the flag to 2, indicating a timeout was hit.

          timer.Dispose();
          sock.Close(); // closing the Socket cancels the async operation.
     }
}

关于.net - 如何处理异步套接字中的超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5973342/

相关文章:

c# - 如何设置电源设置关闭 : never (turn off the display= never, 让计算机进入休眠状态 = 从不),通过 c# 代码

c - 在套接字编程中返回指向结构的指针

.net - 为什么TaskFactory.StartNew Task没有立即启动?

c# - 在 Live SDK 中使用异步/等待

.net - C# .Net 双问题... 6.8 != 6.8?

c# - WCF 终结点错误 : Could not find default endpoint element

.net - Semaphore.WaitOne/Release vs Monitor.Pulse/Wait

python - ZMQ 延迟与 PUB-SUB(慢订阅者)

Java Socket - 管道损坏错误

http - 二郎。异步http请求。如何知道连接何时断开?