package UDPDemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendDemo { public static void main(String[] args) throws IOException { //创建发送端的Socket对象(DatagramSocket) DatagramSocket ds = new DatagramSocket(); //创建字符缓冲输入流对象, //用于存放键盘录入的字符串通过创建InputStreamReader对象,作为参数给到字符缓冲流进行封装 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //创建字符串对象,用于关闭发送端 String line; //对输入的字符进行判断,如果为889直接返回,发送数据结束 while ((line = br.readLine()) != null) { if ("889".equals(line)) { break; } //创建数据,数据打包调用DatagramSocket对象的send方法发送数据 byte[] bytes = line.getBytes(); DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.1.210"), 10086); ds.send(dp); } // 关闭发送端 ds.close(); } }
package UDPDemo; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ReceiveDemo { public static void main(String[] args) throws IOException { //创建接收端的Socket对象(DatagramSocket) DatagramSocket ds = new DatagramSocket(10086); //while死循环,用于一直接收数据 while (true) { //创建新的数据包,用来存放收到的书局 byte[] bytes = new byte[1024]; DatagramPacket dp = new DatagramPacket(bytes, bytes.length); //接受数据 ds.receive(dp); //对数据包解析,打印输出 System.out.println("数据是 " + new String(dp.getData(), 0, dp.getLength())); } } }
原文:https://www.cnblogs.com/521521cm/p/14524008.html