SendDemo:
package com.renhongwei.demo_01; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; /* * UDP数据发送端 */ public class SendDemo { public static void main(String[] args) throws IOException { // 创建socket对象 DatagramSocket ds = new DatagramSocket(); // 创建打包数据 byte[] bys = "Hello,world".getBytes(); int length = bys.length; String host = "renhongwei-pc"; InetAddress address = InetAddress.getByName(host); int port = 10086; DatagramPacket dp = new DatagramPacket(bys,length,address,port); // 发送数据 ds.send(dp); // 释放资源 ds.close(); } }
ReceiveDemo:
package com.renhongwei.demo_01; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /* * UDP接收数据端 */ public class ReceiveDemo { public static void main(String[] args) throws IOException { // 设置端口 int port = 10086; // 创建socket对象 DatagramSocket ds = new DatagramSocket(port); // 创建数据包(接收容器) byte[] bys = new byte[1024]; int length = bys.length; DatagramPacket dp = new DatagramPacket(bys,length); // 调用socket方法接收数据 ds.receive(dp); // 获取IP地址 InetAddress address = dp.getAddress(); String ip = address.getHostAddress(); // 解析数据包 byte[] bys2 = dp.getData(); int length2 = dp.getLength(); String str = new String(bys,0,length2); System.out.println(ip + "----" + str); // 释放资源 ds.close(); } }
时间: 2024-10-10 21:03:39