void StartListening(ref Socket ListeningSocket)
{
// Note: Do not catch exceptions until we reach the main
// listening loop, because <c>StartThread</c> should
// intercept initialization exceptions.
// Establish the local endpoint for the socket (only on localhost)
IPAddress lb = (BindAddress == null)
? (UseIPv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback)
: BindAddress;
IPEndPoint localEndPoint = new IPEndPoint(lb, this.LocalPort);
// Create a TCP/IP socket
AddressFamily af = UseIPv6 ? AddressFamily.InterNetworkV6 :
AddressFamily.InterNetwork;
ListeningSocket = new Socket(af, SocketType.Stream,
ProtocolType.Tcp);
log.Info("Listening to incoming IPv" +
(UseIPv6 ? "6" : "4") + " connections on port " + LocalPort);
// Bind the socket to the local endpoint and listen for incoming
// connections.
ListeningSocket.Bind(localEndPoint);
ListeningSocket.Listen(1000);
// Notify that the listening thread is up and running
IsListening = true;
InitListenFinished.Set();
// Main listening loop starts now
try
{
while (!IsShuttingDown)
{
#if DEBUG_ACCEPT_CONNECTION
log.Debug("Reset signal");
#endif
ListenThreadSwitch.Reset();
if (IsShuttingDown)
break;
#if DEBUG_ACCEPT_CONNECTION
log.Debug("BeginAccept (before)");
#endif
ListeningSocket.BeginAccept(
new AsyncCallback(AcceptCallback), ListeningSocket);
#if DEBUG_ACCEPT_CONNECTION
log.Debug("Wait signal");
#endif
// Wait until a connection is made before continuing
ListenThreadSwitch.WaitOne();
#if DEBUG_ACCEPT_CONNECTION
log.Debug("Received signal");
#endif
}
}
catch (Exception e)
{
log.Error(e);
}
finally
{
log.Debug("Stopped listening on port " + LocalPort);
}
}