在C#中,BeginReceive
方法用于异步接收数据。当你使用BeginReceive
时,你需要提供一个回调方法,该方法将在接收到数据时被调用。以下是一个简单的示例,说明如何使用BeginReceive
处理数据:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
// 创建一个TCP客户端
TcpClient client = new TcpClient("example.com", 80);
// 发送HTTP请求
SendHttpRequest(client);
// 开始异步接收数据
BeginReceiveData(client);
// 保持主线程运行,以便可以接收到数据
Console.ReadLine();
}
static void SendHttpRequest(TcpClient client)
{
NetworkStream stream = client.GetStream();
string request = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n";
byte[] requestBytes = Encoding.ASCII.GetBytes(request);
stream.Write(requestBytes, 0, requestBytes.Length);
}
static void BeginReceiveData(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[4096];
// 异步接收数据
IAsyncResult result = stream.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, null);
// 当接收到数据时,调用回调方法
result.AsyncWaitHandle.ThreadStart(() =>
{
try
{
// 接收数据
int bytesReceived = stream.EndReceive(result);
string response = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
// 处理接收到的数据
Console.WriteLine("Received data:\n" + response);
// 继续接收更多数据
BeginReceiveData(client);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
});
}
}
在这个示例中,我们首先创建一个TCP客户端并连接到服务器。然后,我们发送一个HTTP请求并等待服务器响应。接下来,我们使用BeginReceiveData
方法开始异步接收数据。当接收到数据时,我们调用回调方法,该方法将接收到的数据转换为字符串并打印到控制台。最后,我们递归地调用BeginReceiveData
以继续接收更多数据。