多點傳播:
多點傳播是指把資訊同時傳遞給一組目的位址。它使用的政策是最高效的,因為消息在每條網絡鍊路上隻需傳遞一次,且隻有在鍊路分叉的時候,消息才會被複制。與多點傳播相比,正常的點到單點傳遞被稱作單點傳播。當以單點傳播的形式把消息傳遞給多個接收方時,必須向每個接收者都發送一份資料副本。由此産生的多餘副本将導緻發送方效率低下,且缺乏可擴充性。不過,許多流行的協定——例如XMPP,用限制接收者數量的方法彌補了這一不足。
來自維基百科
代碼實作:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
public class MuiltcastDemo {
private static int PORT = 5555;
private static String MULTICAST_ADDRESS = "225.0.0.1";
static class MulticastClient {
private MulticastSocket socket;
private String id;
private InetAddress group;
private int port;
public MulticastClient(final String id, InetAddress group, int port) throws IOException {
this.id = id;
this.group = group;
this.port = port;
socket = new MulticastSocket(port);
socket.joinGroup(group);
final byte[] buf = new byte[256];
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String msg = new String(packet.getData());
System.out.println("用戶端" + id + "接受到的資料:" + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void send(String msg) {
byte[] bytes = msg.getBytes();
try {
socket.leaveGroup(group);//發送的人不接收多點傳播消息
msg = "用戶端" + id + "發送資料:" + msg;
System.out.println(msg);
socket.send(new DatagramPacket(bytes, bytes.length, group, port));
socket.joinGroup(group);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
MulticastClient mcA = new MulticastClient("A", InetAddress.getByName(MULTICAST_ADDRESS), PORT);
MulticastClient mcB = new MulticastClient("B", InetAddress.getByName(MULTICAST_ADDRESS), PORT);
MulticastClient mcC = new MulticastClient("C", InetAddress.getByName(MULTICAST_ADDRESS), PORT);
mcA.send("Hello!");
TimeUnit.SECONDS.sleep(2);
mcB.send("Hello!");
TimeUnit.SECONDS.sleep(2);
mcC.send("Hello!");
TimeUnit.SECONDS.sleep(2);
}
}