在C#中,實現(xiàn)異步通信通常使用async
和await
關(guān)鍵字。這些關(guān)鍵字允許你編寫異步代碼,從而不阻塞主線程。這里有一個簡單的示例,展示了如何使用async
和await
實現(xiàn)異步通信:
首先,確保你的項目引用了System.Net.Sockets
命名空間,因為我們將使用TCP套接字進(jìn)行通信。
創(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)用程序的性能。