import java.io.*; import java.net.*; public class first { public static void main(String[] args) { // TODO Auto-generated method stub MySend ms = new MySend(); MyRece mr = new MyRece(); Thread th1 = new Thread(ms); Thread th2 = new Thread(mr); th1.start(); th2.start(); } } class MySend implements Runnable { public void run() { DatagramSocket ds = null; try { ds = new DatagramSocket(8888); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 2 确定数据 、 封装成数据包 byte[] data = "udp ge men lai le ".getBytes(); DatagramPacket dp = null; try { dp = new DatagramPacket(data,data.length,InetAddress.getByName("127.0.0.1"),10000); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 3 通过socket服务 将已有的数据包发送出去、通过send方法 try { ds.send(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 4 关闭资源 ds.close(); } } class MyRece implements Runnable { public void run() { // 1 创建udp socket 建立接收端点 DatagramSocket ds = null; try { ds = new DatagramSocket(10000); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 2 定义数据包、用于存储数据 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf,buf.length); // 3 通过服务的 receive 方法将收到的数据存储到数据包中 try { ds.receive(dp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 4 通过数据包中的方法获取其中的数值 String ip = dp.getAddress().getHostAddress(); String data = new String(dp.getData(),0,dp.getLength()); int port = dp.getPort(); System.out.println(ip+"::"+data+"::"+port); // 5 关闭资源 ds.close(); } }
来源:https://www.cnblogs.com/zxl1010/p/11880263.html