Properly Creating / Disposing of Socket connections
-
I've been writing a client / server app for a while now, and in the original version I had a load of exception handling. Recently I've come to rewrite this and I think it's time for me to learn some lessons on what exactly I'm doing. The first part I need to solve is my client connection to a remote Unix server.
_connectionSocket.LocalSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); _connectionSocket.TimeStamp = DateTime.Now; IPEndPoint remoteEndPoint = new IPEndPoint( Dns.GetHostEntry( remoteIp ).AddressList[ 0 ], remotePort ); _connectionSocket.LocalSocket.Connect( remoteEndPoint ); _connectionSocket.LocalSocket.BeginReceive( _connectionSocket.DataBuffer, 0, SocketPacket.BufferSize, SocketFlags.None, OnDataReceived, _connectionSocket );
_connectionSocket is SocketPacket object containing my socket, the buffer etc. I'm following what I've seen done in other comms code. When I disconnect;if( _connectionSocket.LocalSocket != null) { _connectionSocket.LocalSocket.Shutdown( SocketShutdown.Both ); _connectionSocket.LocalSocket.Close( 5 ); }
I'm having issues in that when I'm trying to shutdown, my code is hanging (I know that 5 means seconds to wait to complete sending messages and I don't think that's it). And then I can't establish a new connection, I have to wait a few minutes before the connection is dropped. Can anyone guide me here/