1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public class UDPClient { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(); byte[] buf = "Hello World".getBytes(); InetAddress address = InetAddress.getByName("127.0.0.1"); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 65001); socket.send(packet);
byte[] data = new byte[100]; DatagramPacket receivedPacket = new DatagramPacket(data, data.length); socket.receive(receivedPacket); String content = new String(receivedPacket.getData(), 0, receivedPacket.getLength()); System.out.println(content); } }
|