Java Reference
In-Depth Information
socket
.
send
(
outgoing
);
DatagramPacket
incoming
=
new
DatagramPacket
(
new
byte
[
bufferSize
],
bufferSize
);
// next line blocks until the response is received
socket
.
receive
(
incoming
);
int
numBytes
=
incoming
.
getLength
();
byte
[]
response
=
new
byte
[
numBytes
];
System
.
arraycopy
(
incoming
.
getData
(),
0
,
response
,
0
,
numBytes
);
return
response
;
}
catch
(
IOException
ex
)
{
return
null
;
}
}
public
static
void
main
(
String
[]
args
)
{
InetAddress
host
;
int
port
=
0
;
try
{
host
=
InetAddress
.
getByName
(
args
[
0
]);
port
=
Integer
.
parseInt
(
args
[
1
]);
}
catch
(
RuntimeException
|
UnknownHostException
ex
)
{
System
.
out
.
println
(
"Usage: java UDPPoke host port"
);
return
;
}
try
{
UDPPoke
poker
=
new
UDPPoke
(
host
,
port
);
byte
[]
response
=
poker
.
poke
();
if
(
response
==
null
)
{
System
.
out
.
println
(
"No response within allotted time"
);
return
;
}
String
result
=
new
String
(
response
,
"US-ASCII"
);
System
.
out
.
println
(
result
);
}
catch
(
UnsupportedEncodingException
ex
)
{
// Really shouldn't happen
ex
.
printStackTrace
();
}
}
}
For example, this connects to a daytime server over UDP:
$
java UDPPoke rama.poly.edu 13
Sun Oct 3 13:04:22 2009
This connects to a chargen server:
$
java UDPPoke rama.poly.edu 19
123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuv