我关闭客户端连接时,异步回调方法收到错误

时间:2019-07-19 10:28:20

标签: c#

我关闭客户端的连接时逐步接收替代方法被调用且报错

(汉语翻译)当我关闭客户端的连接时,将调用异步接收回调方法并报告错误。

private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            //获取接收数据长度
            int count = 0;
           // if (socket.Connected)
                count = socket.EndReceive(ar);
            if (count == 0)
            {
                Close();
                return;
            }
            readBuff.writeIdx += count;
            //处理二进制消息
            OnReceiveData();
            //继续接收数据
            if (readBuff.remain < 8)
            {
                //readBuff.MoveBytes();//这句代码没有意义
                readBuff.ReSize(readBuff.length);
            }
            socket.BeginReceive(readBuff.bytes, readBuff.writeIdx,
                    readBuff.remain, 0, ReceiveCallback, socket);
        }
        catch (SocketException ex)
        {
            Debug.Log("Socket Receive fail" + ex.ToString());
        }
    }

结果

//System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
  at System.Net.Sockets.Socket.ThrowIfDisposedAndClosed () [0x0001b] in <c9226b2f33b7421e85bb391f94075e49>:0 
  at System.Net.Sockets.Socket.EndReceive (System.IAsyncResult asyncResult, System.Net.Sockets.SocketError& errorCode) [0x00000] in <c9226b2f33b7421e85bb391f94075e49>:0 
  at System.Net.Sockets.Socket.EndReceive (System.IAsyncResult asyncResult) [0x00000] in <c9226b2f33b7421e85bb391f94075e49>:0 
  at NetManager.ReceiveCallback (System.IAsyncResult ar) [0x00010] in H:\Work\UnitySocket\Chapter6\SocketBook6\Assets\Scripts\framework\NetManager.cs:192 
  at System.Net.Sockets.SocketAsyncResult+<>c.<Complete>b__27_0 (System.Object state) [0x0000b] in <c9226b2f33b7421e85bb391f94075e49>:0 
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00008] in <1f0c1ef1ad524c38bbc5536809c46b48>:0 
  at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in <1f0c1ef1ad524c38bbc5536809c46b48>:0 
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in <1f0c1ef1ad524c38bbc5536809c46b48>:0  occurred

0 个答案:

没有答案