1.服务端
import java.io.IOException; import java.net.*; public class UDPDemo { public static void main(String[] args) { try { String info ="mm"; byte[] bytes = info.getBytes(); /* 数据报*/ DatagramPacket dp = new DatagramPacket( bytes,0,bytes.length, InetAddress.getByName("127.0.0.1"),8888); /* 本程序的端口*/ DatagramSocket socket = new DatagramSocket(9000); socket.send(dp); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2.客户端
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UDPClient { public static void main(String[] args) { byte[] bytes = new byte[1024]; /* 数据报*/ DatagramPacket dp = new DatagramPacket(bytes,bytes.length); try { DatagramSocket socket = new DatagramSocket(8888); socket.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); System.out.println(s); socket.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }