Multicasting
suggest changeMulticasting is a form of datagram delivery. Unlike a unicast datagram, it is not addressed to one client; it is sent to a multicast IP address, and every subscribed client can receive the message.
Example code for a server side:
public class Server {
private DatagramSocket serverSocket;
private String ip;
private int port;
public Server(String ip, int port) throws SocketException, IOException{
this.ip = ip;
this.port = port;
// socket used to send
serverSocket = new DatagramSocket();
}
public void send() throws IOException{
// make datagram packet
byte[] message = ("Multicasting...").getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length,
InetAddress.getByName(ip), port);
// send packet
serverSocket.send(packet);
}
public void close(){
serverSocket.close();
}
}
Example code for a client side:
public class Client {
private MulticastSocket socket;
public Client(String ip, int port) throws IOException {
// important that this is a multicast socket
socket = new MulticastSocket(port);
// join by ip
socket.joinGroup(InetAddress.getByName(ip));
}
public void printMessage() throws IOException{
// make datagram packet to receive
byte[] message = new byte[256];
DatagramPacket packet = new DatagramPacket(message, message.length);
// receive the packet
socket.receive(packet);
// getData() is the whole buffer, including unused trailing bytes; getLength() is the received size
System.out.println(new String(packet.getData()));
}
public void close(){
socket.close();
}
}
Code for running the Server:
public static void main(String[] args) {
try {
final String ip = args[0];
final int port = Integer.parseInt(args[1]);
Server server = new Server(ip, port);
server.send();
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Code for running a Client:
public static void main(String[] args) {
try {
final String ip = args[0];
final int port = Integer.parseInt(args[1]);
Client client = new Client(ip, port);
client.printMessage();
client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Run the Client First: The Client must subscribe to the IP before it can start receiving any packets. If you start the server and call the send() method, and then make a client (& call printMessage()). Nothing will happen because the client connected after the message was sent.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents