Java Reference
In-Depth Information
byte [] buffer = new byte [ MAX_PACKET_SIZE ];
try ( DatagramSocket server = new DatagramSocket ( PORT )) {
DatagramPacket packet = new DatagramPacket ( buffer , buffer . length );
while ( true ) {
try {
server . receive ( packet );
String s = new String ( packet . getData (), 0 , packet . getLength (), "8859_1" );
System . out . println ( packet . getAddress () + " at port "
+ packet . getPort () + " says " + s );
// reset the length for the next packet
packet . setLength ( buffer . length );
} catch ( IOException ex ) {
System . err . println ( ex );
}
} // end while
} catch ( SocketException ex ) {
System . err . println ( ex );
}
}
}
This is a simple class with a single method, main() . It reads the port the server listens
to from the command line. If the port is not specified on the command line, it listens
on port 9. It then opens a DatagramSocket on that port and creates a DatagramPacket
with a 65,507-byte buffer—large enough to receive any possible packet. Then the server
enters an infinite loop that receives packets and prints the contents and the originating
host on the console. There's no particular encoding expected for discard packets. Indeed,
there's no particular reason these packets have to be text at all. I somewhat arbitrarily
picked the Latin-1 ISO 8859-1 encoding because it's ASCII compatible and defines a
character for every byte.
As each datagram is received, the length of packet is set to the length of the data in that
datagram. Consequently, as the last step of the loop, the length of the packet is reset to
the maximum possible value. Otherwise, the incoming packets would be limited to the
minimum size of all previous packets. You can run the discard client on one machine
and connect to the discard server on a second machine to verify that the network is
working.
public void close()
Calling a DatagramSocket object's close() method frees the port occupied by that
socket. As with streams and TCP sockets, you'll want to take care to close the datagram
socket in a finally block:
DatagramSocket server = null
try {
server = new DatagramSocket ();
Search WWH ::




Custom Search