c#

c# beginreceive怎样与beginsend配合使用

小樊
83
2024-12-04 07:22:53
栏目: 编程语言

在C#中,BeginReceiveBeginSend通常用于异步通信操作,例如在网络套接字上进行数据接收和发送。这两个方法都属于System.Net.Sockets.Socket类。要使它们协同工作,您需要执行以下步骤:

  1. 创建一个Socket实例。
  2. 使用BeginReceive开始接收数据。
  3. BeginReceive的回调方法中处理接收到的数据。
  4. 使用BeginSend开始发送数据。
  5. BeginSend的回调方法中处理发送完成的事件。

以下是一个简单的示例,说明如何将BeginReceiveBeginSend配合使用:

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

class AsyncSocketExample
{
    private const int BUFFER_SIZE = 1024;
    private Socket _socket;

    public AsyncSocketExample(Socket socket)
    {
        _socket = socket;
    }

    public void StartListening()
    {
        _socket.BeginAccept(null, null, new AsyncCallback(AcceptCallback), null);
    }

    public void StartSending(string message)
    {
        byte[] sendData = Encoding.ASCII.GetBytes(message);
        _socket.BeginSend(sendData, 0, sendData.Length, null, null, new AsyncCallback(SendCallback), null);
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket handler = (Socket)ar.AsyncState;
        Socket newClient = handler.Accept();

        if (newClient != null)
        {
            Console.WriteLine("New client connected.");
            newClient.BeginAccept(null, null, new AsyncCallback(AcceptCallback), null);

            // Handle the received data in a separate thread
            Task.Run(() => HandleReceivedData(newClient));
        }
    }

    private void SendCallback(IAsyncResult ar)
    {
        Socket handler = (Socket)ar.AsyncState;
        int bytesSent = handler.EndSend(ar);
        Console.WriteLine("Sent {0} bytes.", bytesSent);
    }

    private void HandleReceivedData(Socket client)
    {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRec = client.EndReceive(ar);

        if (bytesRec > 0)
        {
            string data = Encoding.ASCII.GetString(buffer, 0, bytesRec);
            Console.WriteLine("Received: {0}", data);

            // Echo the received data back to the client
            string response = "Server received: " + data;
            byte[] responseBytes = Encoding.ASCII.GetBytes(response);
            client.BeginSend(responseBytes, 0, responseBytes.Length, null, null, new AsyncCallback(SendCallback), null);
        }
        else
        {
            Console.WriteLine("Client disconnected.");
            client.Close();
        }
    }
}

在这个示例中,我们创建了一个AsyncSocketExample类,它使用BeginReceiveBeginSend方法处理客户端的连接和数据传输。当客户端连接时,我们接受连接并在单独的线程中处理接收到的数据。同时,我们可以使用BeginSend将接收到的数据发送回客户端。

0
看了该问题的人还看了