C# SOCKET 客户端异步发送和接收
时间: 2024-10-16 20:11:09 浏览: 36
C# Socket通信(winform) 异步发送消息,服务端客户端通信,可以发送消息和文件并进行接收
5星 · 资源好评率100%
在C#中,使用Socket进行客户端的异步通信通常涉及`SocketAsyncEventArgs`类和`BeginSend`和`BeginReceive`方法。以下是基本的步骤:
1. 创建`Socket`实例并连接到服务器:
```csharp
using System.Net.Sockets;
using System.Threading;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("服务器地址"), 端口号);
socket.Connect(endPoint);
```
2. 初始化`SocketAsyncEventArgs`实例并设置回调:
```csharp
SocketAsyncEventArgs sendArgs = new SocketAsyncEventArgs();
sendArgs.SetBuffer(data, 0, data.Length); // 数据缓冲区
sendArgs.Completed += (sender, e) =>
{
if (e.SocketError == SocketError.Success)
{
Console.WriteLine("发送完成");
}
else
{
Console.WriteLine($"发送失败,错误码:{e.SocketError}");
}
// 发送完成后可以继续请求新的数据发送,或者关闭连接等操作
};
```
3. 异步发送数据:
```csharp
socket.BeginSend(sendArgs, SocketFlags.None, callback: null, state: null);
```
这里,`callback`参数是一个委托,当异步操作完成时会被调用。
4. 对于接收到的数据,你可以创建另一个`SocketAsyncEventArgs`实例,并监听`Receive`事件:
```csharp
SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs();
receiveArgs.Completed += OnReceiveCompleted;
void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
byte[] buffer = new byte[receiveArgs.Buffer.Length];
Buffer.BlockCopy(e.Buffer, 0, buffer, 0, e.BytesTransferred);
string receivedData = Encoding.UTF8.GetString(buffer);
Console.WriteLine($"接收到数据:{receivedData}");
}
else
{
Console.WriteLine($"接收失败,错误码:{e.SocketError}");
}
}
socket.BeginReceive(receiveArgs, SocketFlags.None, callback: null, state: null);
```
在处理完数据后,再次开始接收,直到不再需要连接或达到预期的接收条件。
阅读全文