Receiving Datagrams

Example 5-12 is a program that sits and waits to receive datagrams. When it receives one, it prints out the contents of the datagram and the name of the host that sent it.

To receive a datagram, you must first create a DatagramSocket that listens on a particular port of the local host. This socket can receive only those packets sent to that particular port. Then, you must create a DatagramPacket with a byte buffer into which datagram data is stored. Finally, you call the DatagramSocket.receive( ) method to wait for a datagram to arrive on the specified port. When it does, the data it contains is transferred into the specified buffer, and receive( ) returns. If the datagram contains more bytes than fit into the specified buffer, the extra bytes are discarded. When a datagram arrives, receive( ) also stores the host and port that the datagram was sent from into the packet.

Example 5-12. UDPReceive.java

package je3.net; import java.io.*; import java.net.*; /** * This program waits to receive datagrams sent to 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. **/ public class UDPReceive { public static final String usage = "Usage: java UDPReceive <port>"; public static void main(String args[ ]) { try { if (args.length != 1) throw new IllegalArgumentException("Wrong number of args"); // Get the port from the command line int port = Integer.parseInt(args[0]); ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.