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

TCP Socket一端关闭之后不报异常,而是接受0字节。
我用.net 3.5, VS 2008 开发, TCP Socket通讯,递归调用接受信息。在实际项目中发现当 Socket一端关闭(调用Socket.Close())后,另外一端不是报出异常(我期望是如此),而是不断递归调用接受0字节。我整理了下代码,下面Demo能重现此问题。期望有人能给出解释。
服务器端代码

    class TestServer
    {
        static void Main()
        {
            try
            {
                TCPServer tcpServer = (TCPServer)TCPServer.GetInstance();
                tcpServer.ServerIP = "127.0.0.1";
                tcpServer.ServerPort = 3721;
                tcpServer.CreatListener();
                Console.WriteLine(String.Format("Server is ready with {0}:{1}", tcpServer.ServerIP, tcpServer.ServerPort));
            }           
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
            Console.WriteLine("Press Enter to Exit"); Console.ReadLine();
        }    
    } 

    public abstract class PacketTransferBase
    {
        public PacketTransferBase()
        {            
        }
        private int count = 0;
        /// <summary>
        /// 接收信息
        /// </summary>
        /// <param name="ar"></param>
        protected void ReceiveMessage(IAsyncResult ar)
        {
            try
            {
                StateObject so = (StateObject)ar.AsyncState;
                Socket socket = so.workSocket;                

               &nbs