Java Reference
In-Depth Information
called
theSocket
is constructed. After creating the socket, the program enters an infinite
while
loop that reads user input line by line using
readLine()
.
Example 12-5
is careful,
however, to use only
readLine()
to read data from the console, the one place where it
is guaranteed to work as advertised. Because the discard protocol deals only with raw
bytes, it can ignore character encoding issues.
In the
while
loop, each line is converted to a
byte
array using the
getBytes()
method,
and the bytes are stuffed in a new
DatagramPacket
,
theOutput
. Finally,
theOutput
is
sent over
theSocket
, and the loop continues. If at any point the user types a period on
a line by itself, the program exits. The
DatagramSocket
constructor may throw a
Sock
etException
, so that needs to be caught. Because this is a discard client, you don't need
to worry about data coming back from the server.
public void receive(DatagramPacket dp) throws IOException
This method receives a single UDP datagram from the network and stores it in the
preexisting
DatagramPacket
object
dp
. Like the
accept()
method in the
ServerSock
et
class, this method blocks the calling thread until a datagram arrives. If your program
does anything besides wait for datagrams, you should call
receive()
in a separate
thread.
The datagram's buffer should be large enough to hold the data received. If it's not,
receive()
places as much data in the buffer as it can hold; the rest is lost. Remember
that the maximum size of the data portion of a UDP datagram is 65,507 bytes. (That's
the 65,536-byte maximum size of an IP datagram minus the 20-byte size of the IP header
and the 8-byte size of the UDP header.) Some application protocols that use UDP further
restrict the maximum number of bytes in a packet; for instance, NFS uses a maximum
packet size of 8,192 bytes.
If there's a problem receiving the data,
receive()
may throw an
IOException
. In prac‐
tice, this is rare because problems like dropped packets that would shut down a TCP
stream are silently discarded by the network or network stack before Java ever sees them.
Example 12-6
shows a UDP discard server that receives incoming datagrams. Just for
fun, it logs the data in each datagram to
System.out
so that you can see who's sending
what to your discard server.
Example 12-6. The UDPDiscardServer
import
java.net.*
;
import
java.io.*
;
public
class
UDPDiscardServer
{
public
final
static
int
PORT
=
9
;
public
final
static
int
MAX_PACKET_SIZE
=
65507
;
public
static
void
main
(
String
[]
args
)
{