c# - 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 消息:现有连接被远程主机强行关闭
谢谢你的帮助
解决方案
感谢我从 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; } );
推荐阅读
- c++ - Microsoft C++ 异常:内存位置的 std::out_of_range
- java - 带有 Box2D 的 libgdx Actor 上的输入侦听器
- asp.net-core - 发布 asp.net 核心应用程序时找不到元数据文件
- xml - Jitterbit 问题将 xsd 文件设置为转换目标
- angular - Angular 6自定义管道创建段落的预览
- django - DRF:Api端点不输出所有数据
- python - ValueError:使用 seaborn 时缓冲区的维数错误(预期为 1,得到 2)
- java - Javax 验证未捕获 POJO 的内部字段
- python - python子进程多次提供输入和读取输出[windows]
- node.js - TypeScript 生成错误