温馨提示×

c# beginreceive在哪接收数据

c#
小樊
81
2024-12-04 07:55:52
栏目: 编程语言

在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 = Encoding.ASCII.GetString(socket.ReceiveBuffer, 0, bytesReceived);

        // 输出接收到的数据
        Console.WriteLine("Received data: " + receivedData);

        // 继续接收数据
        socket.BeginReceive(new byte[4096], 0, 4096, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
    }
}

在这个示例中,我们首先创建一个TcpClient实例并连接到服务器。然后,我们发送一个HTTP请求并等待服务器响应。接下来,我们使用BeginReceive方法开始异步接收数据,并将接收到的数据传递给ReceiveCallback方法进行处理。在ReceiveCallback方法中,我们使用EndReceive方法结束异步接收操作,并将接收到的数据转换为字符串。最后,我们继续调用BeginReceive方法以持续接收数据。

0