java.lang.Object
|
+----java.net.DatagramSocket
|
+----java.net.MulticastSocket
多址发送报文端口(socket)类用来发送和接收 IP 多址发送报文。 MulticastSocket 是 (UDP) 报文端口,带有连接因特网上其他多址发送主机的附加功能。
多址发送组由 D 类IP 地址指定,范围在
224.0.0.1 到 239.255.255.255 之间,并包含一个标准
UDP 端口号码。 要想连接一个多址发送组,可以首先创建一个带有所需端口的 MulticastSocket ,
再调用方法 joinGroup(InetAddress
groupAddr) :
// 连接多址发送组并发问候信息
...
byte[] msg = {'H', 'e', 'l', 'l', 'o'};
InetAddress group = InetAddress.getByName("228.5.6.7");
MulticastSocket s = new MulticastSocket(6789);
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg, msg.length,
group, 6789);
s.send(hi);
// 获得响应!
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
...
// OK,我已完成通话 - 脱离该组...
s.leaveGroup(group);
给一个多址发送组发信息时, 所有 预订了该主机和端口的接收者接收该信息(在报文的存活时间内,见下面)。 该 socket 不必是发信息的多址发送组的成员。
当 socket 预定一个多址发送组/端口时, 它会接收到其它主机向该组 /端口发送的报文,就如同该组/端口的其他成员。 socket 通过方法 leaveGroup(InetAddress addr) 退出一个组。 多个 MulticastSocket 可同时预定一个多址发送组和端口,并且它们都会接收到该组的报文。
当前 applet 不允许使用多址发送 socket 。
public MulticastSocket() throws IOException
public MulticastSocket(int port) throws IOException
public void setTTL(byte ttl) throws IOException
DatagramPackets 的存活时间,该时间定义了信息包死亡之前在网络上被转发的 "hops" 数。
ttl 是 无符号 8位数, 并必须属于范围
0
public byte getTTL() throws IOException
public void joinGroup(InetAddress mcastaddr) throws IOException
public void leaveGroup(InetAddress mcastaddr) throws IOException
public void setInterface(InetAddress inf) throws SocketException
public InetAddress getInterface() throws SocketException
public synchronized void send(DatagramPacket p,
byte ttl) throws IOException