private void AcceptConnection(IAsyncResult result) { if (!newClients) { return; } Socket oldSocket = (Socket)result.AsyncState; Socket newSocket = oldSocket.EndAccept(result); TelnetClient client = new TelnetClient((IPEndPoint)newSocket.RemoteEndPoint, DateTime.Now, EClientState.NotLogged); clientList.Add(newSocket, client); Console.WriteLine("TelnetClient connected. (From: " + string.Format("{0}:{1}", client.remoteEndPoint.Address.ToString(), client.remoteEndPoint.Port) + ")"); string output = "-- 接口日志服务器 --\n\r\n\r"; output += "请输入密码:\n\r"; client.clientState = EClientState.Logging; byte[] message = defaltEncoding.GetBytes(output); newSocket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), newSocket); serverSocket.BeginAccept(new AsyncCallback(AcceptConnection), serverSocket); }
private void BackgroundThread() { while (true) { string Input = Console.ReadLine(); if (Input == "clients") { if (clientList.Count == 0) { continue; } int clientNumber = 0; foreach (KeyValuePair <Socket, TelnetClient> client in clientList) { TelnetClient currentClient = client.Value; clientNumber++; Console.WriteLine(string.Format("TelnetClient #{0} (From: {1}:{2}, ECurrentState: {3}, Connection time: {4})", clientNumber, currentClient.remoteEndPoint.Address.ToString(), currentClient.remoteEndPoint.Port, currentClient.clientState, currentClient.connectedAt)); } } if (Input.StartsWith("kill")) { string[] _Input = Input.Split(' '); int clientID = 0; try { if (Int32.TryParse(_Input[1], out clientID) && clientID >= clientList.Keys.Count) { int currentClient = 0; foreach (Socket currentSocket in clientList.Keys.ToArray()) { currentClient++; if (currentClient == clientID) { currentSocket.Shutdown(SocketShutdown.Both); currentSocket.Close(); clientList.Remove(currentSocket); Console.WriteLine("TelnetClient has been disconnected and cleared up."); } } } else { Console.WriteLine("Could not kick client: invalid client number specified."); } } catch { Console.WriteLine("Could not kick client: invalid client number specified."); } } if (Input == "killall") { int deletedClients = 0; foreach (Socket currentSocket in clientList.Keys.ToArray()) { currentSocket.Shutdown(SocketShutdown.Both); currentSocket.Close(); clientList.Remove(currentSocket); deletedClients++; } Console.WriteLine("{0} clients have been disconnected and cleared up.", deletedClients); } if (Input == "lock") { newClients = false; Console.WriteLine("Refusing new connections."); } if (Input == "unlock") { newClients = true; Console.WriteLine("Accepting new connections."); } } }