C#工厂异步套接字错误“在主机上断开连接”

时间:2018-11-29 21:02:51

标签: c# sockets asynchronous factory

 async Task ReceiveFromClient()
        {
            if (this.m_ClientSocket.Connected == true)
            {
                try
                {
                    var asyncResult = this.m_ClientSocket.BeginReceive(m_LocalBuffer, 0, m_LocalBuffer.Length, SocketFlags.None, null, null);
        /* Exception here */ int bytesReceived = await Task<int>.Factory.FromAsync(asyncResult, _ => this.m_ClientSocket.EndReceive(asyncResult)); /* This is the line with Exception */

                    if (bytesReceived != 0)
                    {
                        Console.WriteLine("Packets received");
                        m_LocalSecurity.Recv(m_LocalBuffer, 0, bytesReceived);

                        List<Packet> ReceivedPackets = m_LocalSecurity.TransferIncoming();
                        if (ReceivedPackets != null)
                        {
                            foreach (Packet _pck in ReceivedPackets)
                            {
                                new PacketHandler.PacketFromClientHandler(this, _pck, null);
                            }
                        }

                    }
                    else
                    {
                        this.DisconnectModuleSocket();
                        this.m_delDisconnect.Invoke(ref m_ClientSocket);
                        return;
                    }

                    await Task.Factory.StartNew(this.ReceiveFromClient);

                }
                catch (AggregateException ae)
                {
                    Console.WriteLine(ae);
                }
                catch (SocketException ex)
                {
                    Console.WriteLine($"{ex.Message} ({ex.GetType()})");
                }

                //Exceptions: ArgumentNullException, SocketException, ObjectDisposedException, ArgumentOutOfRangeException
                catch (Exception e)
                {
                    this.DisconnectModuleSocket();
                    this.m_delDisconnect.Invoke(ref m_ClientSocket);
                    return;
                }
            }
        }

在这里,您可以看到我的代码是一个异步TCP套接字,在这里我读取了从客户端到服务器的数据包,一切正常,但是当用户从套接字断开连接时,注释行给了我一个例外。我已经搜索了很多小时,但是找不到我的问题的答案。

我已经尝试捕获异常,但是没有成功。

我需要一些可以在用户断开连接时停止任务并关闭连接的操作。

Visual Studio 2016给我的错误是:

  

异常类型:System.Net.Sockets.SocketException   错误代码:10054   消息:远程主机强行关闭了现有连接

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

感谢我从qqdev <3获得的帮助,只需更改此行即可:

int bytesReceived = await Task<int>.Factory.FromAsync(asyncResult, _ => this.m_ClientSocket.EndReceive(asyncResult));

对此:

int bytesReceived = await Task<int>.Factory.FromAsync(asyncResult, _ => {try { return this.m_ClientSocket.EndReceive(asyncResult); } catch(Exception ex) {} return 0; } );