private void Process() { while (ContinueProcess) { ClientHandler client = null; lock (ConnectionPool.SyncRoot) { if (ConnectionPool.Count > 0) { client = ConnectionPool.Dequeue(); } } if (client != null) { client.Process(); // Provoke client // if client still connect, schedufor later processingle it if (client.Alive) { ConnectionPool.Enqueue(client); } } Thread.Sleep(100); } }
public void StartListening() { Console.WriteLine("Remote Console ready."); ClientService ClientTask; // Client Connections Pool ClientConnectionPool ConnectionPool = new ClientConnectionPool(); // Client Task to handle client requests ClientTask = new ClientService(ConnectionPool); ClientTask.Start(); TcpListener listener = new TcpListener(IPAddress.Any, portNum); try { listener.Start(); int ClientNbr = 0; // Start listening for connections. while (true) { TcpClient handler = listener.AcceptTcpClient(); if (handler != null) { Console.WriteLine("Client#{0} accepted!", ++ClientNbr); // An incoming connection needs to be processed. var clientHandler = new ClientHandler(ClientNbr, handler); OnClientConnected?.Invoke(clientHandler); clientHandler.OnMessageReceived += ClientHandler_OnMessageReceived; ConnectionPool.Enqueue(clientHandler); } else { break; } } listener.Stop(); // Stop client requests handling ClientTask.Stop(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }