我在c#中有一个程序,我在其中创建一个套接字,绑定它,开始监听然后使用beginaccept!但是当我尝试关闭\ shutdown套接字时,我从beginaccept AsyncCallback方法获得异常!
private void start_listening() { main_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iplocal = new IPEndPoint(IPAddress.Any, 11150); main_socket.Bind(iplocal); main_socket.Listen(5); main_socket.BeginAccept(new AsyncCallback(OnClientConnect), null); } private void Disconnect_Click(object sender, EventArgs e) { main_socket.Shutdown(SocketShutdown.Both); main_socket.Close(); } public void OnClientConnect(IAsyncResult asyn) { try { clients[connected_clients] = new Client("CHANGEME", "127.0.0.1", this); clients[connected_clients].Socket = main_socket.EndAccept(asyn); clients[connected_clients].WaitForData(); main_socket.BeginAccept(OnClientConnect, null); } catch (SocketException se) { MessageBox.Show(se.Message); } }
非常感谢!
当main_socket关闭时,将调用OnClientConnect(),但main_socket.EndAccept()应抛出ObjectDisposedException.也许您希望捕获该异常并将其视为"侦听器套接字已关闭"消息.
您的代码的另一个问题是main_socket实际上没有连接到任何东西.在Disconnect_Click()中调用main_socket.Shutdown()可能也会抛出,但这次它应该是一个SocketException,说套接字没有连接.我会删除main_socket.Shutdown()调用.