UDP pocket sender and receiver : UDP Server « Network « Java Tutorial






import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

class PacketReceiver {
  public static void main(String[] args) throws Exception {
    byte[] buffer = new byte[1024];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
    DatagramSocket socket = new DatagramSocket(5002);
    socket.receive(packet);
    System.out.println(packet.getSocketAddress());
    buffer = packet.getData();
    System.out.println(new String(buffer));
  }
}

class PacketSender {

  public static void main(String[] args) throws Exception {
    byte[] buffer = "data".getBytes();
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(
        "localhost", 5002));
    DatagramSocket socket = new DatagramSocket(5003);
    socket.send(packet);
  }
}








19.18.UDP Server
19.18.1.UDP Echo Server With Channels
19.18.2.UDP time server based on New IO
19.18.3.UDP pocket sender and receiver