1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //接收端 public class ReceiveDemo { public static void main(String[] args) throws Exception { //创建接收对象 DatagramSocket receiver = new DatagramSocket(18889); byte[] buffer =new byte[1024]; //接收数据 DatagramPacket dp = new DatagramPacket(buffer,1024); receiver.receive(dp); //获取接收的数据 String msg = new String (dp.getData(),0,dp.getLength()); System.out.println("发送过来的数据:" + msg); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //发送端 public class Send { public static void main(String[] args) throws Exception { String data ="天王盖地虎!"; //创建发送对象 DatagramSocket sender = new DatagramSocket(18888); //发送数据 DatagramPacket dp = new DatagramPacket(data.getBytes(), data.getBytes().length, InetAddress.getLocalHost(), 19989); sender.send(dp); sender.close(); } } |
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
个人编程学习网
本文地址: Java-UDP协议
本文地址: Java-UDP协议
您必须 登录 才能发表评论