//服务端
import java.io.IOException; import java.net.*; public class UdpDemo { public static void main(String[] args) { String info = "welcome to Ganzhou"; byte[] bytes = info.getBytes(); try { //封装一个数据报包 DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getByName("127.0.0.1"),8000); DatagramSocket socket = new DatagramSocket(9000); socket.send(dp); socket.close(); } catch ( UnknownHostException | SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
//客户端
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.io.IOException; import java.net.SocketException; /** * 客户端 */ public class UdpClientDemo { public static void main(String[] args) { byte[] bytes = new byte[1024]; DatagramPacket dp = new DatagramPacket(bytes, bytes.length); try { DatagramSocket socket = new DatagramSocket(8000); System.out.println("正在接收数据"); 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(); } } }