public bool DisconnectClient(int client_id) { try { ClientInServer client = Id_to_Client(client_id); if (client.Disconnect()) { LOG_LINE("SERVER >> Client {0} disconnected.", client_id); } else { LOG_LINE("SERVER >> ERROR: Client {0} cannot be disconnected.", client_id); } // TO DO: Clear deletes all the clients - we must delete only the disconnected client !!!! // clients.Clear(); // clients.TryRemove(client); } catch (Exception e) { LOG_LINE("SERVER >> DisconnectClient():" + e.ToString()); return(false); } return(true); }
// // Private methods // // Listening thread private void ListenForClients() { this.tcpListener.Start(); Socket socket = null; while (serverRun) { LOG_LINE("SERVER >> ListenForClients()-> Listening for clients..."); // Blocks until a client has connected to the server try { while ((serverRun) && (!this.tcpListener.Pending())) { Thread.Sleep(10); } if (serverRun) { socket = this.tcpListener.AcceptSocket(); LOG_LINE("SERVER >> Client socket accepted."); } } catch (Exception e) { serverRun = false; LOG_LINE("SERVER >> ListenForClients()-> ERROR:" + e.ToString()); } if (!serverRun) { LOG_LINE("SERVER >> ListenForClients()-> Server was terminated. "); break; // server was terminated } ClientInServer client = CreateClient(); // Add the socket to the global client sockets list clients[cur_sock_id] = client; // Add also GUI window for the socket // pass the clients log handler delagate(e.g. in the Clients Log form) to this client client.SubscribeLogHandler(logHdrClients); client.SubscribeRecHandler(recHdrClients); // start handling the client - communication thread will be start internally client.StartHandlingClient(cur_sock_id, socket, logHdrClients); LOG_LINE("SERVER >> Client # {0} from IP:{1} at port {2} connected and communication started.", cur_sock_id, ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString(), ((IPEndPoint)(socket.LocalEndPoint)).Port); if (connectHandler != null) { connectHandler(cur_sock_id); } cur_sock_id++; // go listen for the next client } LOG_LINE("SERVER >> ListenForClients()-> Listenning thread finished. "); }