Server.java
package com.zby;import java.net.DatagramPacket;import java.net.DatagramSocket;public class Server { private static boolean running = true; public static void main(String[] args) throws Exception { DatagramSocket server = new DatagramSocket(8888); byte[] buffer = new byte[1024]; DatagramPacket requestPacket = new DatagramPacket(buffer, buffer.length); while (running) { server.receive(requestPacket); String request = new String(requestPacket.getData(), 0, requestPacket.getLength()); System.out.println("request:" + request); System.out.println("InetAddress:" + requestPacket.getAddress()); System.out.println("port:" + requestPacket.getPort()); System.out.println(); String response = "Hello,Client!"; DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getAddress(), requestPacket.getPort()); server.send(responsePacket); } server.close(); }}
Client.java
package com.zby;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class Client { public static void main(String[] args) throws Exception { DatagramSocket client = new DatagramSocket(7777); String request = "Hello,Server!"; DatagramPacket datagramPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, InetAddress.getLocalHost(), 8888); client.send(datagramPacket); byte[] buffer = new byte[1024]; DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length); client.receive(responsePacket); String response = new String(responsePacket.getData(), 0, responsePacket.getLength()); System.out.println("response:" + response); System.out.println("InetAddress:" + responsePacket.getAddress()); System.out.println("port:" + responsePacket.getPort()); System.out.println(); client.close(); }}