Отправка строки от одного клиента другому в c# - PullRequest
0 голосов
/ 21 апреля 2020

У меня есть этот удивительный код, найденный здесь (слегка настроенный)

Клиент:

namespace Client
{
    class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";
        static void Main(string[] args)
        {
            while (true)
            {
                //---data to send to the server---
                string textToSend;
                Console.Write($"String to send: ");
                textToSend = Console.ReadLine();

                //---create a TCPClient object at the IP and port no.---
                TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
                NetworkStream nwStream = client.GetStream();
                byte[] bytesToSend = ASCIIEncoding.UTF8.GetBytes(textToSend);

                //---send the text---
                nwStream.Write(bytesToSend, 0, bytesToSend.Length);

                //---read back the text---
                byte[] bytesToRead = new byte[client.ReceiveBufferSize];
                int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
                Console.WriteLine("Received : " + Encoding.UTF8.GetString(bytesToRead, 0, bytesRead));

                client.Close();
            }
            Console.ReadKey();
        }
    }

Сервер:

class Program
    {
        const int PORT_NO = 5000;
        const string SERVER_IP = "127.0.0.1";

        static void Main(string[] args)
        {
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            while (true)
            {
                //---listen at the specified IP and port no.---
                Console.WriteLine("Listening...");
                listener.Start();

                //---incoming client connected---
                TcpClient client = listener.AcceptTcpClient();

                //---get the incoming data through a network stream---
                NetworkStream nwStream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];

                //---read incoming stream---
                int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

                //---convert the data received into a string---
                string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: " + dataReceived);

                //---write back the text to the client---
                Console.WriteLine("Sending back...");
                nwStream.Write(buffer, 0, bytesRead);
                client.Close();    
            }

            listener.Stop();
            Console.ReadKey();
        }
    }

И он работает без нареканий, но что если я хочу отправить эту строку другому клиенту, а не отправлять обратно? У меня есть идея для подключения 2 клиентов к серверу, а затем отправлять сообщения, или просто указать IP в сообщении. Но я понятия не имею, как это сделать. Любые предложения, или где я должен искать ответ?

Это для науки, ничего профессионального, поэтому, пожалуйста, не обращайте внимания на такие вещи, как недоступный код.

...