在C#中,BeginReceive
和BeginSend
通常用于异步通信操作,例如在网络套接字上进行数据接收和发送。这两个方法都属于System.Net.Sockets.Socket
类。要使它们协同工作,您需要执行以下步骤:
- 创建一个
Socket
实例。 - 使用
BeginReceive
开始接收数据。 - 在
BeginReceive
的回调方法中处理接收到的数据。 - 使用
BeginSend
开始发送数据。 - 在
BeginSend
的回调方法中处理发送完成的事件。
以下是一个简单的示例,说明如何将BeginReceive
与BeginSend
配合使用:
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 = https://www.yisu.com/ask/Encoding.ASCII.GetBytes(message);"hljs">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 = https://www.yisu.com/ask/Encoding.ASCII.GetString(buffer, 0, bytesRec);"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
类,它使用BeginReceive
和BeginSend
方法处理客户端的连接和数据传输。当客户端连接时,我们接受连接并在单独的线程中处理接收到的数据。同时,我们可以使用BeginSend
将接收到的数据发送回客户端。