写一个使用C# Socket.ReceiveAsync方法进行异步接收数据示例
时间: 2023-12-07 10:07:45 浏览: 466
C#基于Socket的TcpClient异步实现和基于Socket的TcpServer异步实现(AsyncTcp).rar
以下是一个使用C# Socket.ReceiveAsync方法进行异步接收数据的简单示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var ip = IPAddress.Parse("127.0.0.1");
var port = 1234;
var client = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
await client.ConnectAsync(ip, port);
Console.WriteLine($"Connected to {ip}:{port}");
while (true)
{
var buffer = new byte[1024];
var receiveResult = await client.ReceiveAsync(buffer, SocketFlags.None);
if (receiveResult == 0)
{
Console.WriteLine("Server disconnected.");
break;
}
var message = Encoding.UTF8.GetString(buffer, 0, receiveResult);
Console.WriteLine($"Received message: {message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
client.Dispose();
}
}
```
该示例创建了一个Socket客户端,连接到IP地址为127.0.0.1,端口为1234的服务器。然后,它进入无限循环,在其中接收从服务器发送的数据,并将其打印到控制台上。当服务器断开连接时,循环将终止。注意,在ReceiveAsync方法中使用了SocketFlags.None,表示不使用任何特殊标志来接收数据。
阅读全文