protected virtual void Listen() { try { m_listener = m_listenerFactory.Create(IPAddress.Any, m_portNumber); m_listener.Start(); Debug.WriteLine($"Listening on port:{m_portNumber}"); while (m_listenContinue) { if (m_listener.Pending()) { lock (m_connections.SyncRoot) { if (m_connections.Count < m_maxConnections) { // blocking call... ITcpConnection conn = null; try { conn = m_tcpConnectionFactory.Create(m_listener.Accept()); conn.Begin(); conn.IdleTimeout += conn_IdleTimeout; m_connections.Add(conn); Debug.WriteLine($"Client connection: {IPAddress.Parse(((IPEndPoint)conn.Client.Socket.RemoteEndPoint).Address.ToString())}"); } catch (Exception ex) { Debug.WriteLine($"Exception caught on ITcpConnection Begin(): {ex}"); if (ex.InnerException != null) { Debug.WriteLine($"Inner Exception: {ex.InnerException}"); } if (conn != null) { CleanupConnection(conn); } } } else { Debug.WriteLine("Max Server Connections Reached."); using (var client = m_listener.AcceptTcpClient()) { using (var writer = new StreamWriter(client.GetStream())) { writer.Write("Unable to connect. Max server connections reached."); writer.Flush(); } } } } } else { Thread.Sleep(100); } } } catch (Exception ex) { Trace.WriteLine(ex); Debug.WriteLine("Server::ShutdownServer() called"); ShutdownServer(); Debug.WriteLine("Server::StartupServer() called"); StartupServer(); } }