AI智能
改变未来

C# UDP关闭时出现 “ 由于以前的关闭调用,套接字在那个方向已经关闭,发送或接收数据的请求没有被接受。”

UDP启动之后使用 clientSocket.BeginReceive接收数据

但是在关闭时经常出现 “由于以前的关闭调用,套接字在那个方向已经关闭,发送或接收数据的请求没有被接受。”的错误,

[code]//关闭socketif (clientSocket != null){try{if (clientSocket.Connected){//关闭Socket之前,首选需要把双方的Socket Shutdown掉clientSocket.Shutdown(SocketShutdown.Both);//Shutdown掉Socket后主线程停止10ms,保证Socket的Shutdown完成Thread.Sleep(10);//关闭客户端Socket,清理资源clientSocket.Close();Log.Debug(\"ClientSocket--->关闭成功\");}}catch (System.Exception e){Log.Error($\"ClientSocket关闭失败--------->  {e.Message}\");}clientSocket = null;}

但偶尔又不报错,很是费解。

初步怀疑是因为在关闭了socket之后,但在异步接收进程中没有被立即停止,仍然访问了socket,导致了访问冲突

so,我在Socket.BeginReceive和关闭客户端时加了个lock进行限制

[code]private readonly static object _lock = new object();private static bool applicationIsQuitting = false;protected static bool ApplicationIsQuitting{get{lock(_lock){return applicationIsQuitting;}}set{applicationIsQuitting = value;}}
[code]void AsyncCallBack(IAsyncResult ar){try{if (ApplicationIsQuitting)return;if (clientSocket != null){len = clientSocket.EndReceive(ar);if (len > 0){ReadMsg(buffer, len, ProcessDataCallBack);}}}catch (SocketException e){Log.Error(e.Message);SetNetStates(NetState.Error);}clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, AsyncCallBack, buffer);}
[code]private void Close(){ApplicationIsQuitting = true;if (clientSocket != null){try{if (clientSocket.Connected){//关闭Socket之前,首选需要把双方的Socket Shutdown掉clientSocket.Shutdown(SocketShutdown.Both);//Shutdown掉Socket后主线程停止10ms,保证Socket的Shutdown完成Thread.Sleep(10);//关闭客户端Socket,清理资源clientSocket.Close();Log.Debug(\"ClientSocket--->关闭成功\");}}catch (System.Exception e){Log.Error($\"ClientSocket关闭失败--------->  {e.Message}\");}clientSocket = null;}}

加了lock之后没再出现上述问题

记录一下解决方法,哪位大佬认为解决思路有问题,可以留言改正,以免误人子弟,谢谢

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C# UDP关闭时出现 “ 由于以前的关闭调用,套接字在那个方向已经关闭,发送或接收数据的请求没有被接受。”