void AcceptCallback(IAsyncResult ar)
{
if (IsShuttingDown)
return;
// Have we really changed thread?
if (ListeningThread.ManagedThreadId ==
System.Threading.Thread.CurrentThread.ManagedThreadId)
{
// No! Give me a new thread!
new Thread(() => AcceptCallback(ar)).Start();
return;
}
// Get the socket that handles the client request
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Signal the main thread to continue
ListenThreadSwitch.Set();
#if DEBUG_ACCEPT_CONNECTION
log.Debug("\tAcceptCallback sent signal");
#endif
// Create the state object
HttpSocket state = new HttpSocket(handler);
state.id = ++LastClientId;
lock (ConnectedSockets)
ConnectedSockets[state.id] = state;
AbstractProxyLogic proxy = null;
try
{
proxy = OnClientStart(state);
} catch (Exception e) { log.Error(e); }
if (proxy == null)
{
CloseSocket(state);
return;
}
// No need for asynchronous I/O from now on
try
{
while (proxy.LogicLoop())
if (IsShuttingDown || state.IsSocketDead())
break;
log.Debug("Shutting down socket");
}
catch (System.Net.Sockets.SocketException e)
{
log.Warn(e);
}
catch (TrotiNet.IoBroken e)
{
log.Warn(e);
}
catch (Exception e)
{
log.Error(e);
log.Debug("Closing socket on error");
}
CloseSocket(state);
}