如何处理异步套接字中的超时? [英] How to handle timeout in Async Socket?

查看:28
本文介绍了如何处理异步套接字中的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a code that using async socket to send message to client and expecting response from it. If the client did not reply in a specified internal it will considers timeout. Some of the article in Internet suggest to use WaitOne, but this will blocks the thread and defers the purpose of using I/O completion.

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

What is the best way to handle timeout in async socket?

 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 操作.

You can’t timeout or cancel asynchronous Socket operations.

你所能做的就是启动你自己的Timer,它关闭Socket——回调将被立即调用,EndX函数将如果你调用它,返回一个 ObjectDisposedException.举个例子:

All you can do is start your own Timer which closes the Socket—the callback will then be immediately called and the EndX function will come back with an ObjectDisposedException if you call it. Here's an example:

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.
     }
}

这篇关于如何处理异步套接字中的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆