Java Reference
In-Depth Information
a datagram with no data at all, bugs in some Java implementations require that you add
at least one byte of data to the datagram. The simple servers we're currently considering
ignore this data.
Once a
UDPPoke
object has been constructed, clients call its
poke()
method to send an
empty
outgoing
datagram to the target and read its response. The response is initially
set to null. When the expected datagram appears, its data is copied into the
response
field. This method returns null if the response doesn't come quickly enough or never
comes at all.
The
main()
method merely reads the host and port to connect to from the command
line, constructs a
UDPPoke
object, and pokes it. Most of the simple protocols that this
client suits will return ASCII text, so this example attempts to convert the response to
an ASCII string and print it.
Example 12-7. The UDPPoke class
import
java.io.*
;
import
java.net.*
;
public
class
UDPPoke
{
private
int
bufferSize
;
// in bytes
private
int
timeout
;
// in milliseconds
private
InetAddress
host
;
private
int
port
;
public
UDPPoke
(
InetAddress
host
,
int
port
,
int
bufferSize
,
int
timeout
)
{
this
.
bufferSize
=
bufferSize
;
this
.
host
=
host
;
if
(
port
<
1
||
port
>
65535
)
{
throw
new
IllegalArgumentException
(
"Port out of range"
);
}
this
.
port
=
port
;
this
.
timeout
=
timeout
;
}
public
UDPPoke
(
InetAddress
host
,
int
port
,
int
bufferSize
)
{
this
(
host
,
port
,
bufferSize
,
30000
);
}
public
UDPPoke
(
InetAddress
host
,
int
port
)
{
this
(
host
,
port
,
8192
,
30000
);
}
public
byte
[]
poke
()
{
try
(
DatagramSocket
socket
=
new
DatagramSocket
(
0
))
{
DatagramPacket
outgoing
=
new
DatagramPacket
(
new
byte
[
1
],
1
,
host
,
port
);
socket
.
connect
(
host
,
port
);
socket
.
setSoTimeout
(
timeout
);