O'Reilly logo

Java™ Network Programming and Distributed Computing by Michael Reilly, David Reilly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required