protected internal void AddConnection(ClientObject clientObject) { clients.Add(clientObject); BroadcastMessage(clientObject, "вошел в чат!"); }
// прослушивание входящих подключений protected internal void Listen() { try { var port = _port; var localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); server.Start(); Console.WriteLine("Сервер запущен"); var tempClient = new TcpClient(); while (true) { if (server.Pending() == true) { tempClient = server.AcceptTcpClient(); var data = ReadMessage(tempClient); if (ServerCommands.TextToCommand(data.ToString(), out string restText) == Commands.ConnectToServer) { if (isUniqueName(restText)) { ClientObject client = new ClientObject(tempClient, restText); AddConnection(client); SendMessage(Commands.AcceptConnection, "", client.Stream); Console.WriteLine("Enter connection from {0}", tempClient.Client.RemoteEndPoint); } else { SendMessage(Commands.DiscardConnection, "Выберите другое имя", tempClient.GetStream()); tempClient.Close(); } } } for (int i = 0; i < clients.Count; i++) { if (clients[i].Client.Available > 0) { var data = ReadMessage(clients[i].Client); string clientsMessage; Commands clientCommand = ServerCommands.TextToCommand(data.ToString(), out clientsMessage); string response = ""; switch (clientCommand) { case Commands.None: clientCommand = Commands.BadRequest; response = "не знаю такую команду"; break; case Commands.NewChatMessage: clientCommand = Commands.Message_OK; BroadcastMessage(clients[i], clientsMessage); break; case Commands.ConnectToServer: clientCommand = Commands.BadRequest; response = "Вы уже вошли в чат"; break; case Commands.Quit: clients[i].Close(); RemoveConnection(clients[i].Id); --i; continue; default: clientCommand = Commands.BadRequest; response = "Не известная или не уместная команда!!"; break; } SendMessage(clientCommand, response, clients[i].Stream); } } System.Threading.Thread.Sleep(200); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadKey(); Disconnect(); } }
protected internal void AddConnection(ClientObject clientObject) { clients.Add(clientObject); }