Java 组播

时间:2021-10-19 06:22:01

MulticastSocketServer.java

 package cn.edu.buaa.multicast;

 import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException; /**
* One thing that we need to take into consideration here, is that there are
* specific addresses that allow us to use a MulticastSocket are limited,
* specifically in the range of 224.0.0.0 to 239.255.255.255. Some of them are
* reserved, like 224.0.0.0. The address that we are using, 224.0.0.3, can be
* used safely.
*/
public class MulticastSocketServer { final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888; public static void main(String[] args) throws UnknownHostException, InterruptedException {
// Get the address that we are going to connect to.
InetAddress addr = InetAddress.getByName(INET_ADDR); // Open a new DatagramSocket, which will be used to send the data.
try (DatagramSocket serverSocket = new DatagramSocket()) {
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i; // Create a packet that will contain the data
// (in the form of bytes) and send it.
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(), msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket); System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

MulticastSocketClient.java

 package cn.edu.buaa.multicast;

 import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException; public class MulticastSocketClient {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888; public static void main(String[] args) throws UnknownHostException {
// Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(INET_ADDR); // Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256]; // Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try (MulticastSocket clientSocket = new MulticastSocket(PORT)) {
// Joint the Multicast group.
clientSocket.joinGroup(address); while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket); String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}