I have an asynchronous socket server and client. If I tell the client to make 20,000 connections to the server I receive “No connection could be made because the target machine actively refused it” for about 25-30% of the connections. This is totally to be expected as I am hammering the listening socket and the backlog queue is filling up.
The question I have is: What do I do when I get this exception? How should I handle the connections, should I be shutting down and closing the socket and then trying to reconnect? Or will TCP try to reconnect via its own mechanism within the protocol?
Here is my code OnConnected function which is the AsyncCallbak for BeginConnect() and it is where I am handling the exception:
void OnConnected(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
try
{
client.EndConnect(ar);
SocketState state = new SocketState(client, m_certValidationCallback);
state.sslStream.BeginAuthenticateAsClient(m_remoteHostName, m_clientCertificates, m_sslProtocols, m_checkCertificateRevocation,
m_onAuthenticateAsClient, state);
}
catch (Exception ex)
{
//m_connectionCallback(this, new SecureConnectionResults(ex));
//What do I do here?
if (client != null)
{
client.Shutdown(SocketShutdown.Both); //This causes an exception
client.Close();
client.Dispose();
}
}
}
Trying to shutdown the socket in the catch, causes another exception: “A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied”
According to this exception, it appears the socket is not connected. Once again, is it going to try to reconnect on its own based on the TCP protocol? Or should I just re-queue the connection and try again?
I would catch a more specific exception, and not call
Shutdown()under this condition. TCP will not reconnect for you. You will have to retry this connection yourself.