如何处理异步套接字超时?

| 我有一个代码,该代码使用异步套接字将消息发送到客户端,并期望其响应。如果客户端未在指定的内部答复,则将认为超时。 Internet上的某些文章建议使用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
    
已邀请:
您无法超时或取消异步“ 1”操作。 您所能做的就是启动自己的
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.
     }
}
    

要回复问题请先登录注册