c# 实现简单udp数据的发送和接收

服务端代码

static void Main(string[] args)
{
  UdpClient client = null;
  string receiveString = null;
  byte[] receiveData = null;
  //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点
  IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);

  while (true)
  {
    client = new UdpClient(11000);
    receiveData = client.Receive(ref remotePoint);//接收数据
    receiveString = Encoding.Default.GetString(receiveData);
    Console.WriteLine(receiveString);
    client.Close();//关闭连接
  }
}

 

客户端代码

static void Main(string[] args)
{
  string sendString = null;//要发送的字符串
  byte[] sendData = null;//要发送的字节数组
  UdpClient client = null;

  IPAddress remoteIP = IPAddress.Parse("123.45.6.7"); //假设发送给这个IP
  int remotePort = 11000;
  IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点

  while (true)
  {
    sendString = Console.ReadLine();
    sendData = Encoding.Default.GetBytes(sendString);

    client = new UdpClient();
    client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
    client.Close();//关闭连接
  }
}

 

转载于:https://www.cnblogs.com/longzhankunlun/p/6251436.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在C#实现UDP数据发送接收到同一个端口,您可以使用UdpClient来完成。以下是一个简单的示例代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; class Program { static void Main() { // 创建UDP客户端 UdpClient udpClient = new UdpClient(); // 设置本地IP和端口 IPAddress localIP = IPAddress.Parse("127.0.0.1"); int localPort = 12345; // 绑定本地IP和端口 udpClient.Client.Bind(new IPEndPoint(localIP, localPort)); // 启动接收数据的线程 var receiveThread = new System.Threading.Thread(() => { while (true) { // 接收数据 IPEndPoint remoteEP = null; byte[] data = udpClient.Receive(ref remoteEP); // 处理接收到的数据 string message = Encoding.UTF8.GetString(data); Console.WriteLine($"接收到来自 {remoteEP.Address}:{remoteEP.Port} 的消息:{message}"); } }); receiveThread.Start(); // 发送数据 string sendMsg = "Hello, UDP!"; byte[] sendData = Encoding.UTF8.GetBytes(sendMsg); IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); int remotePort = 12345; udpClient.Send(sendData, sendData.Length, new IPEndPoint(remoteIP, remotePort)); // 等待用户输入任意键退出程序 Console.ReadKey(); // 关闭UDP客户端 udpClient.Close(); } } ``` 在上述代码中,首先创建了一个UdpClient对象,然后通过调用Bind方法将其绑定到指定的本地IP和端口。接下来,启动了一个线程来循环接收数据,使用Receive方法接收数据,并将其转换为字符串进行处理。然后,使用Send方法发送数据到指定的远程IP和端口。最后,通过调用Close方法关闭UdpClient对象。 请注意,本示例代码中将本地IP设置为"127.0.0.1",端口设置为12345,您可以根据实际需求进行修改。 希望能对您有所帮助!如果您有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值