溫馨提示×

c# beginreceive怎樣與beginsend配合使用

c#
小樊
113
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女