首页 > 解决方案 > C#工厂异步套接字错误“主机断开连接”

问题描述

 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 消息:现有连接被远程主机强行关闭

谢谢你的帮助

标签: c#socketsasynchronousfactory

解决方案


感谢我从 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; } );

推荐阅读