日期:2014-05-20  浏览次数:20839 次

有关socket关闭时报“无法访问已经释放的对象”的问题
我做了个socket服务器,有开启和关闭两种状态,关闭情况下客户端不能访问,只有开启了才能访问。问题是每当我要关闭服务器的时候,总会报说“无法访问已经释放的对象”,让我感到十分郁闷,请各位高手多多帮忙,我是新接触socket的,有很多东西都不太清楚。
以下是我的代码:
                public     void   StartListening()
                {
                       
                        //   Establish   the   local   endpoint   for   the   socket.
                        //   The   DNS   name   of   the   computer
                        //设置服务器的IP地址,网络端口和终结点
                        IPHostEntry   ipHostInfo   =   Dns.Resolve(Dns.GetHostName());
                        IPAddress   ipAddress   =   ipHostInfo.AddressList[0];
                        IPEndPoint   localEndPoint   =   new   IPEndPoint(ipAddress,   11000);
                        //   Create   a   TCP/IP   socket.
                        //建立服务器类型
                        listener   =   new   Socket(AddressFamily.InterNetwork,   SocketType.Stream,   ProtocolType.Tcp);
                        //   Bind   the   socket   to   the   local   endpoint   and   listen   for   incoming   connections.
                        try
                        {
                                //绑定连接终结点并开始侦听
                                listener.Bind(localEndPoint);
                                listener.Listen(10);

                                //   Start   an   asynchronous   socket   to   listen   for   connections.
                                //建立异步SOCKET来侦听传入的连接信息
                                listener.BeginAccept(new   AsyncCallback(AcceptCallback),   listener);              
                        }
                        catch   (Exception   e)
                        {
                                MessageBox.Show(e.ToString());