FileDocCategorySizeDatePackage
UDPReceive.javaAPI DocExample1910Sat Jun 02 02:44:14 BST 2001None

UDPReceive

public class UDPReceive extends Object
This program waits to receive datagrams sent the specified port. When it receives one, it displays the sending host and prints the contents of the datagram as a string. Then it loops and waits again.

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)

    try {
      if (args.length != 1) 
        throw new IllegalArgumentException("Wrong number of arguments");

      // Get the port from the command line
      int port = Integer.parseInt(args[0]);

      // Create a socket to listen on the port.
      DatagramSocket dsocket = new DatagramSocket(port);

      // Create a buffer to read datagrams into.  If anyone sends us a 
      // packet containing more than will fit into this buffer, the excess
      // will simply be discarded!
      byte[] buffer = new byte[2048];
      

      // Now loop forever, waiting to receive packets and printing them out.
      for(;;) {
        // Create a packet with an empty buffer to receive data
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Wait to receive a datagram
        dsocket.receive(packet);

        // Convert the contents to a string, and display them
        String msg = new String(buffer, 0, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ": " + msg);
      }
    }
    catch (Exception e) {
      System.err.println(e);
      System.err.println("Usage: java UDPReceive <port>");
    }