c#

c# beginreceive如何处理异步数据

小樊
83
2024-12-04 07:15:51
栏目: 编程语言

在C#中,BeginReceive方法用于异步接收数据。它通常与IAsyncResult接口一起使用,以便在接收到数据时执行回调函数。以下是一个简单的示例,说明如何使用BeginReceive处理异步数据:

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

class AsyncTcpClient
{
    private const int BufferSize = 4096;
    private readonly TcpClient _client;
    private readonly byte[] _receiveBuffer = new byte[BufferSize];

    public AsyncTcpClient(string server, int port)
    {
        _client = new TcpClient(server, port);
    }

    public void StartListening()
    {
        _client.BeginReceive(_receiveBuffer, 0, BufferSize, SocketFlags.None, OnReceive, null);
    }

    private void OnReceive(IAsyncResult result)
    {
        if (result.IsCompleted)
        {
            // Handle the received data here
            string receivedData = Encoding.UTF8.GetString(_receiveBuffer, 0, BufferSize);
            Console.WriteLine("Received data: " + receivedData);

            // Continue receiving data
            _client.BeginReceive(_receiveBuffer, 0, BufferSize, SocketFlags.None, OnReceive, null);
        }
        else
        {
            // Handle any errors that occurred during the receive operation
            Exception exception = result.Exception;
            Console.WriteLine("Error: " + exception.Message);
        }
    }

    public void StopListening()
    {
        _client.Close();
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        AsyncTcpClient client = new AsyncTcpClient("example.com", 80);
        client.StartListening();

        // Simulate some work while waiting for data
        await Task.Delay(5000);

        client.StopListening();
    }
}

在这个示例中,我们创建了一个AsyncTcpClient类,它使用BeginReceive方法异步接收数据。当接收到数据时,OnReceive回调函数会被调用。在回调函数中,我们可以处理接收到的数据,然后再次调用BeginReceive以继续接收更多数据。

请注意,这个示例使用了async/await语法,这使得异步代码更容易编写和理解。在实际应用中,你可能需要根据你的需求对这个示例进行修改。

0
看了该问题的人还看了