接收
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
try
{
// 监听的端口号
int port = 11000;
// 使用UdpClient监听指定端口
using (UdpClient udpClient = new UdpClient(port))
{
Console.WriteLine($"UDP Server is listening on port {port}...");
while (true)
{
// 尝试接收数据
IPEndPoint remoteEP = null; // 用于存储发送方的终结点信息
byte[] data = udpClient.Receive(ref remoteEP); // 阻塞直到接收到数据
// 解码接收到的数据并打印
string receivedMessage = Encoding.UTF8.GetString(data);
Console.WriteLine($"Received message from {remoteEP.Address}:{remoteEP.Port}: {receivedMessage}");
}
}
}
catch (SocketException se)
{
Console.WriteLine($"SocketException: {se.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
}
}
发送
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
internal class Program
{
static void Main(string[] args)
{
try
{
// 目标IP地址和端口号
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 11000;
IPEndPoint iPEndPoint=new IPEndPoint(ipAddress, port);
// 创建UdpClient实例
using (UdpClient udpClient = new UdpClient())
{
// 发送的数据
string message = "Hello, UDP Server!";
byte[] data = Encoding.UTF8.GetBytes(message);
// 发送数据包
udpClient.Send(data, data.Length, iPEndPoint);
Console.WriteLine($"Sent: {message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}