Java Reference
In-Depth Information
IAN'S BASIC STEPS: UDP CLIENT
UDP is a bit more involved, so I'll list the basic steps for generating a UDP client:
1. Create a
DatagramSocket
with no arguments (the form that takes two arguments is used
on the server).
3. Create one or more
DatagramPacket
objects; these are wrappers around a byte array that
contains data you want to send and is filled in with data you receive.
4. If you did not
connect()
the socket, provide the
InetAddress
and port when construct-
ing the
DatagramPacket
.
5. Set the packet's length and use
sock.send(packet)
to send data to the server.
6. Use
sock.receive()
to retrieve data.
So why would we even use UDP? UDP has a lot less overhead than TCP, which can be par-
ticularly valuable when sending huge amounts of data over a reliable local network or a few
hops on the Internet. Over long-haul networks, TCP is probably preferred because TCP
handles retransmission of lost packets for you. And obviously, if preserving record boundar-
ies makes your life easier, that may be a reason for considering UDP.
used in
Reading and Writing Textual Data
.
Because UDP has no real notion of “connection,”
the client typically initiates the “conversation,” which sometimes means sending an empty
packet; the UDP server uses the address information it gets from that to return its response.
Example 13-8. DaytimeUDP.java
public
public class
DaytimeUDP
{
/** The UDP port number */
public
class
DaytimeUDP
public final
final static
static
int
int
DAYTIME_PORT
=
13
;
/** A buffer plenty big enough for the date string */
protected
protected final
final static
static
int
int
PACKET_SIZE
=
100
;
/** The main program that drives this network client.
* @param argv[0] hostname, running daytime/udp server