Java Reference
In-Depth Information
Example 12-1. A daytime protocol client
import
java.io.*
;
import
java.net.*
;
public
class
DaytimeUDPClient
{
private
final
static
int
PORT
=
13
;
private
static
final
String
HOSTNAME
=
"time.nist.gov"
;
public
static
void
main
(
String
[]
args
)
{
try
(
DatagramSocket
socket
=
new
DatagramSocket
(
0
))
{
socket
.
setSoTimeout
(
10000
);
InetAddress
host
=
InetAddress
.
getByName
(
HOSTNAME
);
DatagramPacket
request
=
new
DatagramPacket
(
new
byte
[
1
],
1
,
host
,
PORT
);
DatagramPacket
response
=
new
DatagramPacket
(
new
byte
[
1024
],
1024
);
socket
.
send
(
request
);
socket
.
receive
(
response
);
String
result
=
new
String
(
response
.
getData
(),
0
,
response
.
getLength
(),
"US-ASCII"
);
System
.
out
.
println
(
result
);
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
}
}
}
Typical output is much the same as if you connected with TCP:
$
java DaytimeUDPClient
56375 13-04-11 19:55:22 50 0 0 843.6 UTC(NIST) *
UDP Servers
A UDP server follows almost the same pattern as a UDP client, except that you usually
receive before sending and don't choose an anonymous port to bind to. Unlike TCP,
there's no separate
DatagramServerSocket
class.
For example, let's implement a daytime server over UDP. Begin by opening a datagram
socket on a well-known port. For daytime, this port is 13:
DatagramSocket
socket
=
new
DatagramSocket
(
13
);
As with TCP sockets, on Unix systems (including Linux and Mac OS X) you need to be
running as root in order to bind to a port below 1024. You can either use
sudo
to run
the program or simply change the port to something 1024 or higher.
Next, create a packet into which to receive a request. You need to supply both a
byte
array in which to store incoming data, the offset into the array, and the number of bytes
to store. Here you set up a packet with space for 1,024 bytes starting at 0: