public void BroadcastMessage(Guid extraID, string message) //распространение сообщения { BasicMethods.Print(message); foreach (var user in ClientList) { if (user.ID != extraID) { BasicMethods.WriteMessage(user.UserStream, message); } } }
static void Connect() //выполняем, если юзер решает подключиться { TcpClient client = null; NetworkStream netStream = null; Thread listeningThread = null; try { Console.ForegroundColor = ConsoleColor.Gray; Console.Write("\nВведи свое имя: "); Console.ForegroundColor = ConsoleColor.Green; string name = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Gray; /*Console.WriteLine("Хорошо. Сначала необходимо ввести координаты сервера. В любой момент можно ввести " + * "'выйти', чтобы вернуться (и словить ошибку программы, которую у меня не получается обработать." + * " UPD: получилось)."); * client = User.TryConnect(name);*///подключение client = User.TryConnect2(name); if (client == null) { throw new ReturnException(); } netStream = client.GetStream(); string serverName = BasicMethods.ReadMessage(netStream); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine($"Сервер '{serverName}' приветствует тебя!\n"); listeningThread = new Thread(() => //поток, в котором принимаем сообщения { while (true) { string message = BasicMethods.ReadMessage(netStream); Console.SetCursorPosition(0, Console.CursorTop); BasicMethods.Print(message); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write(name + ": "); Console.ForegroundColor = ConsoleColor.Green; } }); listeningThread.Start(); Console.WriteLine("Теперь ты можешь писать в чат, просто написав текст сообщения и нажав Enter.\n"); while (true) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write(name + ": "); Console.ForegroundColor = ConsoleColor.Green; string message = Console.ReadLine(); //пишем сообщения if (message == "выйти") { throw new ReturnException(); } else { BasicMethods.WriteMessage(netStream, message); } } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("\nК сожалению, плохой код творца привел к ужасающей ошибке: \n" + e.Message + "\n" + "Программа сделает все, что сможет, чтобы стабилизировать ситуацию."); } finally { if (listeningThread != null) { listeningThread.Abort(); } if (client != null) { client.Close(); } if (netStream != null) { netStream.Close(); } Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Нажми любую клавишу, чтобы продолжить."); Console.ReadLine(); } }