基于UDP套接字的Echo服务器
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** from 时 代 J a v a - nowjava.com**/ public class Main { public static void main(String[] args) throws Exception { DatagramSocket udpSocket = new DatagramSocket(5555, InetAddress.getByName("localhost")); System.out.println("Created UDP server socket at " + udpSocket.getLocalSocketAddress() + "..."); while (true) { System.out.println("Waiting for a UDP packet" + " to arrive..."); DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); udpSocket.receive(packet); displayPacketDetails(packet); udpSocket.send(packet); } } public static void displayPacketDetails(DatagramPacket packet) {/* 来自 NowJava.com - 时 代 Java*/ // Get the message byte[] msgBuffer = packet.getData(); int length = packet.getLength(); int offset = packet.getOffset(); int remotePort = packet.getPort(); InetAddress remoteAddr = packet.getAddress();