Java Reference
In-Depth Information
USN: uuid:34567890-1234-1010-8000-544249cb49fd
X-AV-Server-Info: av=5.0; hn=""; cn="Sony Corporation";
mn="Internet TV Box NSZ-GT1"; mv="1.0";
It appears that my Google TV is very chatty, sending an announcement about once a
second. Most devices only announce when they're first connected to the network, or
when they're queried by another device.
Now let's consider sending multicast data.
Example 13-2
is a
MulticastSender
class
that reads input from the command line and sends it to a multicast group. It's fairly
simple, overall.
Example 13-2. MulticastSender
import
java.io.*
;
import
java.net.*
;
public
class
MulticastSender
{
public
static
void
main
(
String
[]
args
)
{
InetAddress
ia
=
null
;
int
port
=
0
;
byte
ttl
=
(
byte
)
1
;
// read the address from the command line
try
{
ia
=
InetAddress
.
getByName
(
args
[
0
]);
port
=
Integer
.
parseInt
(
args
[
1
]);
if
(
args
.
length
>
2
)
ttl
=
(
byte
)
Integer
.
parseInt
(
args
[
2
]);
}
catch
(
NumberFormatException
|
IndexOutOfBoundsException
|
UnknownHostException
ex
)
{
System
.
err
.
println
(
ex
);
System
.
err
.
println
(
"Usage: java MulticastSender multicast_address port ttl"
);
System
.
exit
(
1
);
}
byte
[]
data
=
"Here's some multicast data\r\n"
.
getBytes
();
DatagramPacket
dp
=
new
DatagramPacket
(
data
,
data
.
length
,
ia
,
port
);
try
(
MulticastSocket
ms
=
new
MulticastSocket
())
{
ms
.
setTimeToLive
(
ttl
);
ms
.
joinGroup
(
ia
);
for
(
int
i
=
1
;
i
<
10
;
i
++)
{
ms
.
send
(
dp
);
}
ms
.
leaveGroup
(
ia
);
}
catch
(
SocketException
ex
)
{
System
.
err
.
println
(
ex
);
}
catch
(
IOException
ex
)
{
System
.
err
.
println
(
ex
);