首页 > 解决方案 > 如何在 c# 上使用异步连接通过套接字发送多条消息

问题描述

我正在尝试将 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

我正在尝试做的是调整客户端应用程序并使其能够在不关闭客户端应用程序的情况下向服务器发送多条消息。我正在尝试无限测试循环,但是当我发送第二条消息时,我收到了错误:

错误 这是我在客户端应用程序上的连接方法:

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());
                }
            }

}

应该注意的是,我在套接字编程方面没有太多经验,所以我不确定 connect 方法是否是进入和解决问题的正确位置。服务器应用程序和客户端应用程序的其余代码是相同的,我只更改了连接方法和一些验证,这应该不是问题。

我试着只循环这个代码块:

// 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);

但我得到了:

已建立的连接中止

标签: c#socketsasyncsocket

解决方案


推荐阅读