溫馨提示×

c# accept怎樣實現(xiàn)異步通信

c#
小樊
83
2024-09-24 17:56:06
欄目: 編程語言

在C#中,實現(xiàn)異步通信通常使用asyncawait關(guān)鍵字。這些關(guān)鍵字允許你編寫異步代碼,從而不阻塞主線程。這里有一個簡單的示例,展示了如何使用asyncawait實現(xiàn)異步通信:

  1. 首先,確保你的項目引用了System.Net.Sockets命名空間,因為我們將使用TCP套接字進(jìn)行通信。

  2. 創(chuàng)建一個名為AsyncCommunication的類,并在其中定義一個名為StartAsyncCommunication的方法:

using System;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace AsyncCommunication
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await StartAsyncCommunication("127.0.0.1", 12345);
        }

        static async Task StartAsyncCommunication(string serverAddress, int serverPort)
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverAddress, serverPort);

                Console.WriteLine("Connected to server.");

                // Send and receive data asynchronously
                await SendAndReceiveData(client);
            }

            Console.WriteLine("Disconnected from server.");
        }

        static async Task SendAndReceiveData(TcpClient client)
        {
            // Send data to the server
            var message = "Hello, server!";
            var data = Encoding.ASCII.GetBytes(message);
            await client.GetStream().WriteAsync(data, 0, data.Length);

            // Receive data from the server
            var receivedData = new byte[1024];
            var receivedBytes = await client.GetStream().ReadAsync(receivedData, 0, receivedData.Length);

            // Convert received data to a string
            var receivedMessage = Encoding.ASCII.GetString(receivedBytes);
            Console.WriteLine("Received from server: " + receivedMessage);
        }
    }
}

在這個示例中,我們創(chuàng)建了一個TCP客戶端,連接到指定的服務(wù)器地址和端口。然后,我們使用SendAndReceiveData方法異步發(fā)送和接收數(shù)據(jù)。這個方法首先將一條消息發(fā)送到服務(wù)器,然后等待從服務(wù)器接收數(shù)據(jù)。接收到的數(shù)據(jù)被轉(zhuǎn)換為字符串并輸出到控制臺。

注意,我們在Main方法和StartAsyncCommunication方法上使用了async關(guān)鍵字,這樣我們就可以在這些方法中使用await關(guān)鍵字等待異步操作完成。這使得我們的代碼不會阻塞主線程,從而提高了應(yīng)用程序的性能。

0