日期:2014-05-17  浏览次数:20940 次

Socket通信死循环问题~大家帮忙分析~有源码
奇怪,在执行下面代码的时候,我开了个客户端每10毫秒发送一次数据,服务端就接收一个数据,但运行大约20几个小时以后,即使我关掉发送数据的客户端,服务器端依然能够接收到数据,一直在死循环,奇怪了晕,大家帮忙分析分析原因,感激不尽~~

C# code

private void BeginReceive()
        {
            try
            {
                StateObject so = new StateObject(this.mSocket);

                mSocket.BeginReceive(so.Buffer, Session.OFFSET, so.Buffer.Length, SocketFlags.None, this.ReceiveCallBack, so);
            }
            catch (Exception ex)
            {
                TriggerErrorEvent(ex);
            }
        }
        private void ReceiveCallBack(IAsyncResult result)
        {
            try
            {
                StateObject so = (StateObject)result.AsyncState;

                int dataLength = so.Socket.EndReceive(result);

                Logger.Debug(string.Format("Read Message Successed, SessionID:{0} Count {1}", this.SessionID, this.mReadCount++));

                so.Socket.BeginReceive(so.Buffer, Session.OFFSET, so.Buffer.Length, SocketFlags.None, this.ReceiveCallBack, so);
            }
            catch (Exception ex)
            {
                TriggerErrorEvent(ex);
            }
        }



------解决方案--------------------
加个条件试试:

C# code
 private void ReceiveCallBack(IAsyncResult result)
        {
            try
            {
                StateObject so = (StateObject)result.AsyncState;

                int dataLength = so.Socket.EndReceive(result);
                if (dataLength > 0)
                {
                    Logger.Debug(string.Format("Read Message Successed, SessionID:{0} Count {1}", this.SessionID, this.mReadCount++));

                    so.Socket.BeginReceive(so.Buffer, Session.OFFSET, so.Buffer.Length, SocketFlags.None, this.ReceiveCallBack, so);
                }
            }
            catch (Exception ex)
            {
                TriggerErrorEvent(ex);
            }
        }