Unable to close socket after BeginAccept method

I have a program in C # in which I create a socket by binding it, start listening, and then with beginaccept! but then when I try to close the \ shutdown socket, I get exceptions from the beginaccept AsyncCallback method!

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); } } 

many thanks!

+4
source share
3 answers

When main_socket is closed, OnClientConnect () is called, but main_socket.EndAccept () should throw an ObjectDisposedException. Perhaps you want to catch this exception and treat it like the message "Close listener socket".

Another problem with your code is that main_socket is not actually related to anything. A call to main_socket.Shutdown () on Disconnect_Click () can also be fired, but this time it should be a SocketException saying that the socket is not connected. I would remove this call to main_socket.Shutdown ().

+6
source

An old topic, but one solution: keep a local variable to keep track of when you "close / close" the socket. I am using _isShutdown .

When you start listening to a socket, set _isShutDown = False;
Before closing the outlet, set _isShutdown = True;

In the EndAccept(iar) function, call only

  socket.EndAccept() when _isShutdown is false <pre><code> 
 if (_isShutdown == false) { someWorkSocket = listenSocket.EndAccept(iaSyncResult); //... } else { //socket is closed, and we shouldn't use it. Should erase this else clause.. } 

+1
source

"To cancel the pending call to the BeginAccept method, close Socket. When the Close method is called during an asynchronous operation, the callback provided to the BeginAccept method is called . A subsequent call to the EndAccept method will raise an ObjectDisposedException to indicate that the operation has been canceled."

Socket.BeginAccept Method (AsyncCallback, Object)

the correct way could be:
1) create a client socket on the server, connect to the listening socket, after successful completion EndAccept close it
2) the method suggested by MSDN is to simply handle this exception as

0
source

All Articles