接收端
package com.zy.demo2; import java.io.File; import java.io.FileOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPReceive { public static void main(String[] args) throws Exception { //1创建码头 DatagramSocket datagramSocket = new DatagramSocket(9999);//双方约定的 //2创建集装箱 // byte b[]=new byte[1024];//空的字节数组 // DatagramPacket datagramPacket = new DatagramPacket(b, b.length); // // // //3收货 // datagramSocket.receive(datagramPacket);//线程阻塞!!!(没收到时) //----------------------------- byte[] aa = new byte[1]; FileOutputStream fileOutputStream = new FileOutputStream(new File("E:\接收的文件\1.png")); do { DatagramPacket datagramPacket = new DatagramPacket(aa, 0, aa.length); if(datagramPacket.getLength()!=1){ break; } datagramSocket.receive(datagramPacket); System.out.println(datagramPacket.getLength()); fileOutputStream.write(datagramPacket.getData()); } while (true); System.out.println("接收完成"); //--------------------------------------- //4查看货物 // System.out.println(new String(b)); //5释放资源 datagramSocket.close(); } }
发送端
package com.zy.demo2; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; public class UDPSend { public static void main(String[] args) throws Exception { //1创建码头 DatagramSocket datagramSocket = new DatagramSocket(); //2创建集装箱 // String data="中国食用油"; // byte[] bytes = data.getBytes(); //3发送数据 //根据名字获取主机(机器互联) InetAddress byName = InetAddress.getByName("192.168.219.61");//getByName("127.0.0.1")也可以写ip,不一定非得是主机名 // DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, byName, 9999); // datagramSocket.send(datagramPacket); byte bb[]=new byte[1];//udp容易丢包,为了降低损失,字节数组调整小些 FileInputStream fileInputStream = new FileInputStream(new File("E:\13.png")); int read = fileInputStream.read(bb); while(read!=-1){ DatagramPacket datagramPacket = new DatagramPacket(bb, bb.length, byName, 9999); datagramSocket.send(datagramPacket); read = fileInputStream.read(bb); } //4释放资源 datagramSocket.close(); } }
程序一个bug:接收端接收完数据时JVM还在运行着,找不到合适的方法让退出JVM