The UDP Classes

Java's support for UDP is contained in two classes, and A DatagramSocket is used to send and receive DatagramPackets. Since UDP is connectionless, streams are not used. You must fit your data into packets of no more than about 60,000 bytes. You can manually split the data across multiple packets if necessary.

The DatagramPacket class is a wrapper for an array of bytes from which data will be sent or into which data will be received. It also contains the address and port to which the packet will be sent.

The DatagramSocket class is a connection to a port that does the sending and receiving. Unlike TCP sockets, there is no distinction between a UDP socket and a UDP server socket. The same DatagramSocket can both and receive. Also unlike TCP sockets, a DatagramSocket can send to multiple, different addresses. The address to which data goes is stored in the packet, not in the socket.

UDP ports are separate from TCP ports. Each computer has 65,536 UDP ports as well as its 65,536 TCP ports. You can have a ServerSocket bound to TCP port 20 at the same time as a DatagramSocket is bound to UDP port 20. Most of the time it should be obvious from context whether or not I'm talking about TCP ports or UDP ports.

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified April 18, 1997