在C#中,BeginReceive
方法用于异步接收数据。它通常与Socket
类的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请求
string request = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n";
NetworkStream stream = client.GetStream();
byte[] requestBytes = Encoding.ASCII.GetBytes(request);
stream.Write(requestBytes, 0, requestBytes.Length);
// 开始异步接收数据
stream.BeginReceive(new byte[4096], 0, 4096, SocketFlags.None, new AsyncCallback(ReceiveCallback), stream);
// 等待用户输入,以便在接收到数据之前不会退出程序
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
// 关闭客户端
client.Close();
}
static void ReceiveCallback(IAsyncResult ar)
{
// 获取Socket实例
Socket socket = (Socket)ar.AsyncState;
// 结束异步接收操作
int bytesReceived = socket.EndReceive(ar);
// 将接收到的数据转换为字符串
string receivedData = https://www.yisu.com/ask/Encoding.ASCII.GetString(socket.ReceiveBuffer, 0, bytesReceived);"Received data: " + receivedData);
// 继续接收数据
socket.BeginReceive(new byte[4096], 0, 4096, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
}
在这个示例中,我们首先创建一个TcpClient
实例并连接到服务器。然后,我们发送一个HTTP请求并等待服务器响应。接下来,我们使用BeginReceive
方法开始异步接收数据,并将接收到的数据传递给ReceiveCallback
方法进行处理。在ReceiveCallback
方法中,我们使用EndReceive
方法结束异步接收操作,并将接收到的数据转换为字符串。最后,我们继续调用BeginReceive
方法以持续接收数据。