Esempio n. 1
0
        public void ListenForConnections() //функция, в которой мы ждем подключения
        {
            Thread givingDirectionThread = new Thread(GiveConnections);

            givingDirectionThread.Start();
            Listener.Start();
            while (true)
            {
                TcpClient     newTcpClient = Listener.AcceptTcpClient();
                NetworkStream newStream    = newTcpClient.GetStream();
                string        newName      = BasicMethods.ReadMessage(newStream);
                BasicMethods.WriteMessage(newStream, ServerName);
                Client newClient = new Client //добавляем нового клиента
                {
                    UserName   = newName,
                    ID         = Guid.NewGuid(),
                    UserClient = newTcpClient,
                    UserStream = newStream
                };
                ClientList.Add(newClient);
                BroadcastMessage(newClient.ID, newName + " присоединился к чату.");
                Thread newClientThread = new Thread(new ParameterizedThreadStart(ListenToClient));
                newClientThread.Start(newClient); //поток, в котором от клиента нам будут приходить сообщения
            }
        }
Esempio n. 2
0
 public void BroadcastMessage(Guid extraID, string message) //распространение сообщения
 {
     BasicMethods.Print(message);
     foreach (var user in ClientList)
     {
         if (user.ID != extraID)
         {
             BasicMethods.WriteMessage(user.UserStream, message);
         }
     }
 }
Esempio n. 3
0
        static TcpClient TryConnectFirstVersion(string ip, int port, string name) //подключение первой версии (часть)
        {
            TcpClient rezult = null;

            try
            {
                rezult = new TcpClient(ip, port);
                NetworkStream ns = rezult.GetStream();
                BasicMethods.WriteMessage(ns, name);
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("Ты успешно подключился к серверу!");
            }
            catch
            {
                //Console.ForegroundColor = ConsoleColor.Gray;
                //Console.WriteLine("К сожалению, данный адрес и порт не задействован ни одним сервером. Попробуй еще.");
            }
            return(rezult);
        }
Esempio n. 4
0
        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();
            }
        }