有关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());
}
}
public void AcceptCallback(IAsyncResult ar)
{
// Get the socket that handles the client request.
//获取传入的客户端信息
Socket listene = (Socket)ar.AsyncState;
Socket handler = listene.EndAccept(ar); //关闭时总是在这里报错
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
listBox_IPAddress.Items.Add(handler.RemoteEndPoint.ToString());
//获取客户端数据
StateObject state = new StateObject();
state.workSocket = handler;
ht.Add(handler.RemoteEndPoint, handler);
Receive(handler);
}
private void button_Start_Click(object sender, EventArgs e)
{
//判断服务器是否已经开启
if (!ISListen)
{
StartListening();
ISListen = true;
}
else
{
MessageBox.Show("服务器已经启动!","系统提示");
}
}
/// <summary>
/// 关闭所有的客户端会话,与所有的客户端连接会断开
/// </summary>
public virtual void CloseAllClient()
{
foreach (Socket client in ht.Values)
{
client.Close();
}
ht.Clear();
}
private void button_Stop_Click(object sender, EventArgs e)
{
if (ISListen)
{
//这个条件语句,一定要在关闭所有客户端以前调用
//否则在EndConn会出现错误
ISListen = false;
//关闭数据连接,负责客户端会认为是强制关闭连接
if (listener.Connected)
{
listener.Shutdown(SocketShutdown.Both);
}
CloseAllClient();
//清理资源
listener.Close();
ht = null;
}
else
{
MessageBox.Show("服务器已经关闭!","系统提示");
}
}