So i know there are a lot of articles out there on this topic and i did read a lot of them i would say but for some reason im sure my code is not doing what it is supposed to do.
I want to close a connection between my Server and my Client. Now on the serverside i start the disconnect with this code
public void shutdown() { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); } And on the Client side i have some troubles understanding how i get to the disconnect what i believe is happening is the following: in my async receive callback i should get an error since the server started a shutdown sequence and i have to handle that (right???) so my code for the client looks like this: ReceiveCallback:
private void ReceiveCallback(IAsyncResult result) { int bytesRecieved = 0; byte[] tempBuff; //Try to receive But if a Socket error occures disconnect otherwise start Receiving again try { bytesRecieved = _socket.EndReceive(result); } catch (SocketException sockEx) { Disconnect(sockEx); return; } catch (ObjectDisposedException disposeEx) { Disconnect(disposeEx); return; } catch (Exception ex) { StartReceive(); return; } if (bytesRecieved == 0) { StartReceive(); return; } tempBuff = new byte[bytesRecieved]; Buffer.BlockCopy(_buffer, 0, tempBuff, 0, bytesRecieved); StartReceive(); _packHandler.handlePacket(tempBuff); } Disconnect:
public void Disconnect() { if (!_socket.Connected) { return; } _socket.BeginDisconnect(false, DisconnectCallback, null); } DisconnectCallback
private void DisconnectCallback(IAsyncResult result) { _socket.EndDisconnect(result); _socket.Close(); } (The Disconnect Method is overloaded so if i get an exception it puts up a messageBox and then also calls Disconnect. Just so i know what happened.)
Where am i wrong and what can i improve uppon ???
I tried the code and it seemed to work but i then looked with netstat if all sockets are closed and the client socket was not. It was in FIN_WAIT_2 which means that it (or the server???) did not yet send the FIN packet right ? Oh and then i tried it again with this line changed:
if (bytesRecieved == 0) { StartReceive(); return; } TO
if (bytesRecieved == 0) { Disconnect; return; } which then threw an exception on the serverside and on the clientside the client said that the connection was closed by the server ???
EDIT: Even when i have closed both Programs Netstat still shows the port in a WAITING status. what does that tell me ?