// This method is the main loop of the ConnectionManager class. It listens for incoming // connections then delegates them to Client Handlers public void Listen() { // Create a server socket on the provided IP and PORT and an empty client socket Log("Creating new TcpListener on " + SERVERIP.ToString() + ", Port: " + STARTPORT.ToString() + "."); serverSocket = new TcpListener(SERVERIP, STARTPORT); clientSocket = default(TcpClient); // Initializes the server socket Log("Starting server socket."); serverSocket.Start(); Log("Server started!"); Log("Ready to establish connection."); // Initializes the current connection count connectionCount = 0; // While this is supposed to keep looping while (keepRunning) { // If there's a pending connection if (serverSocket.Pending()) { // And if the number of active handlers is currently under the maximum allowed if (activeHandlers.Count < maxThreads) { // Accept the incoming connection clientSocket = serverSocket.AcceptTcpClient(); // Increment the connection counter connectionCount += 1; Log("New client connected. Assigned to new thread."); // Initialize a new client handler to handle the new connection ClientHandler client = new ClientHandler(); // Add the new handler to the list of active handlers activeHandlers.Add(client); // Start the new client handler client.startClient(clientSocket, connectionCount, this, logQueue); } // If the current number of active handlers has reached the maximum allowed print a log entry else Log("Maximum running threads reached. Cannot create more connections."); } // If no connections are pending, sleep the thread to allow for other tasks else Thread.Sleep(100); } // If no longer supposed to be running, stop the server socket serverSocket.Stop(); Log("Listener closed."); }
// This method is to be called by a client handler when it is no longer needed. public void HandlerIsDone(ClientHandler caller) { // Removes the client handler from the list of active handlers activeHandlers.Remove(caller); }