Как отправить несколько сообщений через сокет с помощью асинхронного соединения на C # - PullRequest
0 голосов
/ 23 декабря 2018

Я пытаюсь адаптировать пример кода Microsoft для:

"Сокет асинхронного сервера" https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

и "Сокет асинхронного клиента" https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

я пытаюсь адаптировать клиентское приложение и сделать его способным отправлять несколько сообщений на сервер, не закрывая клиентское приложение.Я пытался с бесконечным циклом тестирования, но когда я отправил второе сообщение, я получил ошибку:

The error Вот мой метод подключения в клиентском приложении:

public void connect()
        {

            while (true)
            {

                // Conectarse a un dispositivo remoto  
                try
                {



                        // Establish the remote endpoint for the socket
                        IPEndPoint direccion = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 45000);

                        // Create a TCP/IP socket.  
                        Socket client = new Socket(direccion.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                        // Connect to the remote endpoint.  
                        client.BeginConnect(direccion, new AsyncCallback(ConnectCallback), client);
                        connectDone.WaitOne();

                        // Send test data to the remote device.  
                        Console.WriteLine("Write your message bellow");
                        String data_s = Console.ReadLine();
                        Send(client, data_s);
                        sendDone.WaitOne();

                        // Receive the response from the remote device.  
                        Receive(client);
                        receiveDone.WaitOne();

                        // Write the response to the console.  
                        Console.WriteLine("Response received : {0}", response);

                        // Release the socket.  
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                    }


                catch (Exception e)
                {
                    Console.WriteLine("Aqui esta el error");
                    Console.WriteLine(e.ToString());
                }
            }

}

Следует отметить, что у меня нет большого опыта в программировании сокетов, поэтому я не уверен, является ли метод подключения правильным местом для решения проблемы.Остальная часть кода серверного приложения и клиентского приложения одинакова, я только изменил метод подключения и пару проверок, которые не должны быть проблемой.

Я попытался только зациклить этот блок кода:

// Send test data to the remote device.  
                        Console.WriteLine("Write your message bellow");
                        String data_s = Console.ReadLine();
                        Send(client, data_s);
                        sendDone.WaitOne();

                        // Receive the response from the remote device.  
                        Receive(client);
                        receiveDone.WaitOne();

                        // Write the response to the console.  
                        Console.WriteLine("Response received : {0}", response);

но я получил:

Estabilished connection aborted

...