5.6. User Datagram Protocol Example
To demonstrate how UDP packets are sent and received, we'll compile and run two small examples. The first will bind to a local port, read a packet, and display its contents and addressing information. The second example will send the packet read by the first.
Code for PacketReceiveDemo
import java.net.*; import java.io.*; // Chapter 5, Listing 1 public class PacketReceiveDemo { public static void main (String args[]) { try { System.out.println ("Binding to local port 2000"); // Create a datagram socket, bound to the // specific port 2000 DatagramSocket socket = new DatagramSocket(2000); System.out.println ("Bound to local port " + socket.getLocalPort()); // Create a datagram packet, containing a // maximum ...
Get Java™ Network Programming and Distributed Computing 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.