播数据报套接字类用于发送和接收 IP 多播包。MulticastSocket 是一种 (UDP) DatagramSocket,它具有加入 Internet 上其他多播主机的“组”的附加功能。 多播组通过 D 类 IP 地址和标准 UDP 端口号指定。D 类 IP 地址在 224.0.0.0 和 239.255.255.255 的范围内(包括两者)。地址 224.0.0.0 被保留,不应使用。, p7 Y' R% {6 ?9 _1 ~+ o9 K
可以通过首先使用所需端口创建 MulticastSocket,然后调用 joinGroup(InetAddress groupAddr) 方法来加入多播组:
( |/ e2 {! O) |3 K' T // join a Multicast group and send the group salutations; \8 I. Q. P. Y. f
...
7 R _7 c2 u l7 W% h9 q8 t( Q String msg = "Hello";
; O+ v; _- m$ ^$ [- P" f) W InetAddress group = InetAddress.getByName("228.5.6.7");
$ M& g% e' ~ F/ C s& g MulticastSocket s = new MulticastSocket(6789);
0 I5 W8 p0 ]$ ]% i s.joinGroup(group);8 S* r9 K1 u$ |# [/ i; P3 |& y3 u/ y9 W( x
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(),
( z8 ?" Q% o8 v& c group, 6789);
7 w; ~6 O" I5 V7 K+ H3 Q% ~ s.send(hi);9 A) a5 W8 y* A1 A( v
// get their responses!
5 h0 n5 M" x8 S byte[] buf = new byte[1000];! \! T3 B: |, E, o& t
DatagramPacket recv = new DatagramPacket(buf, buf.length);. m. o6 I" U. Q* T0 G
s.receive(recv);( U1 f4 Q: _8 x$ s
...7 M4 ^+ g: Y+ `/ j4 b4 O& F
// OK, I'm done talking - leave the group...
, e; ^- z7 P* G. P. f* X s.leaveGroup(group);/ u8 O: T0 J6 U& }" V" m- P
将消息发送到多播组时,该主机和端口的所有预定接收者都将接收到消息(在数据包的生存时间范围内,请参阅下文)。套接字不必成为多播组的成员即可向其发送消息。
0 {9 l) N: L( g! J; j# B 当套接字预定多播组/端口时,它将接收由该组/端口的其他主机发送的数据报,像该组和端口的所有其他成员一样。套接字通过 leaveGroup(InetAddress addr) 方法放弃组中的成员资格。多个 MulticastSocket 可以同时预定多播组和端口,并且都会接收到组数据报。% Z" P7 q$ ]" [, }* i0 n6 l
同时,不允许 applet 使用多播套接字。 |