Some Useful Applications

In this section, you’ll see several Internet servers and clients that use DatagramPacket and DatagramSocket. Some of these will be familiar from the last two chapters because many Internet protocols have both TCP and UDP implementations. When an IP packet is received by a host, the host determines whether the packet is a TCP packet or a UDP datagram by inspecting the IP header. As I said earlier, there’s no connection between UDP and TCP ports; TCP and UDP servers can share the same port number without problems. By convention, if a service has both TCP and UDP implementations, it uses the same port for both, though there’s no technical reason this has to be the case.

Simple UDP Clients

Several Internet services need to know only the client’s address and port; they discard any data the client sends in its datagrams. Daytime, quote of the day, time, and chargen are four such protocols. Each of these responds the same way, regardless of the data contained in the datagram, or indeed regardless of whether there actually is any data in the datagram. Clients for these protocols simply send a UDP datagram to the server and read the response that comes back. Therefore, let’s begin with a simple client called UDPPoke, shown in Example 13.5, that sends an empty UDP packet to a specified host and port and reads a response packet from the same host.

The UDPPoke class has three private fields. The bufferSize field specifies how large a return packet is expected. An 8,192-byte ...

Get Java Network Programming, Second 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.