iveAsync一起重用SocketAsyncEventArgs

iveAsync一起重用SocketAsyncEventArgs

本文介绍了与ReceiveAsync一起重用SocketAsyncEventArgs会导致无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个仅使用一个套接字的简单套接字客户端.所以我想我可以为所有接收操作重用一个SocketAsyncEventArgs.只要连接插座,它就可以正常工作.当服务器断开连接时,客户端将在控制台中进入一个无限的垃圾邮件发送循环,垃圾邮件收集成功".

I'm writing a simple socket client which uses only one socket. So I figured I could reuse a single SocketAsyncEventArgs for all receive operations. It's working fine as long as the socket is connected. When the server disconnects, the client will enter a infinite receive loop spamming "Receive Success" in the console.

e.SocketError!= SocketError.当套接字断开连接时成功为真吗?

Shouldn't e.SocketError != SocketError.Success be true when the socket is disconnected?

这是代码的一部分:

private void Completed(object sender, SocketAsyncEventArgs e)
{
   if (e.SocketError != SocketError.Success)
      status = 0;

   System.Console.WriteLine(e.LastOperation + " " + e.SocketError);

   if (status == 1)
   {
      switch (e.LastOperation)
      {
         case SocketAsyncOperation.Connect:
            ProcessConnect(e);
            break;
         case SocketAsyncOperation.Receive:
            ProcessReceive(e);
            break;
         case SocketAsyncOperation.Send:
            ProcessSend(e);
            break;
         default:
            status = 0;
            break;
      }
   }

   if (status != 1)
      CloseSocket();
}

private void ProcessReceive(SocketAsyncEventArgs e)
{
   if (!socket.ReceiveAsync(e))
      Completed(null, e);
}

推荐答案

如果为套接字设置了字节流,则可能会收到零字节的回调,这表明套接字已正常关闭,并且不再读取任何字节.只需在您的代码中进行检查即可,例如

If your socket is set up for a byte stream then you may get a callback with zero bytes, this indicates that a graceful closure of the socket has occurred and that no more bytes will ever be read. Simply check for this in your code, e.g.

private void ProcessReceive( SocketAsyncEventArgs e )
{
    AsyncUserToken token = e.UserToken as AsyncUserToken;
    if( e.ByteTransferred > 0 && e.SocketError == SocketError.Success )
    {
        // .. process normally ..
    }
    else
    {
        CloseClientSocket( e );
    }
}

private void CloseClientSocket( SocketAsyncEventArgs e )
{
    AsyncUserToken token = e.UserToken as AsyncUserToken;
    try
    {
        token.Socket.Shutdown( SocketShutdown.Send );
    }
    // throws error if it's already closed
    catch( Exception ) {}
    token.Socket.Close();
}

当然,您还需要阻止客户端尝试使用套接字,但是我敢肯定您可以解决这一问题.

Of course you'll also need to stop your client from trying to use the socket, but I'm sure you can work that part out.

这篇关于与ReceiveAsync一起重用SocketAsyncEventArgs会导致无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:01