DatagramPacket(byte[] buf, int length, InetAddress address, int port) DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) DatagramPacket(byte[] buf, int length, SocketAddress address) DatagramPacket(byte[] buf, int length) DatagramPacket(byte[] buf, int offset, int length) 其中前面四个是为构造发送的数据报而用的,因为他们有InetAddress或者SocketInetAddress作为接收端点的地址,后面一个则是为了接受数据报用的。
public class TimeServer { final private static int DAYTIME_PORT = 13; public static void main(String args[]) throws IOException { DatagramSocket socket = new DatagramSocket(DAYTIME_PORT); while (true) { byte buffer[] = new byte[256]; DatagramPacket packet =new DatagramPacket(buffer, buffer.length); socket.receive(packet); String date = new Date().toString(); buffer = date.getBytes(); // Get response address/port // for client from packet InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buffer, buffer.length, address, port); socket.send(packet); } } }
import java.io.*; import java.net.*;
public class GetTime { final private static int DAYTIME_PORT = 13; public static void main(String args[]) throws IOException { if (args.length == 0) { System.err.println("Please specify daytime host"); System.exit(-1); } String host = args[0]; byte message[] = new byte[256]; InetAddress address = InetAddress.getByName(host); System.out.println("Checking at: " + address); DatagramPacket packet = new DatagramPacket(message, message.length, address, DAYTIME_PORT); DatagramSocket socket = new DatagramSocket(); socket.send(packet); packet =new DatagramPacket(message, message.length); socket.receive(packet); String time = new String(packet.getData()); System.out.println(The time at "+ host + " is: " + time); socket.close(); } }