MulticastSocket

java.net.MulticastSocket Example

In this example we are going to explain how to use MulticastSocket in Java, in order to enable a server to easily send information to multiple clients, which are all connected to the same port and address. We will describe the whole process, by creating both the server and the client, and guide you through the main concepts that need to be understood to create this type of applications.

 

 

 

1. MulticastSocket Server

We are going to use a DatagramSocket,  to enable the server to send packets of information to the client/clients. A datagram, by definition, is “an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed”. Essentially, we are opening a DatagramSocket in order to send DatagramPacket messages to the client. We are using the datagram classes (instead of standard sockets) because they allow us to broadcast information to multiple clients, that are all connected to a MulticastSocket.

Let’s see the code of the server:

MulticastSocketServer.java

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

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();
        }
    }
}

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.

2. MulticastSocket Client

Regarding the client, we are going to move a little bit differently. We are going to create a client class, that will accept incoming messages from the server, and then we are going to duplicate this class. The point here is that by using the same code, we can connect to the server seamlessly, while having as many clients as we like.

Let’s see the code of the client:

MulticastSocketClient.java

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();
        }
    }
}

First, we start the client, which will keep waiting for incoming packets of information. As soon as we start the server, it will send the information packets and the client will receive them and print the information on the screen.

Server Output

Server sent packet with msg: Sent message no 0
Server sent packet with msg: Sent message no 1
Server sent packet with msg: Sent message no 2
Server sent packet with msg: Sent message no 3
Server sent packet with msg: Sent message no 4

Client Output

Socket 1 received msg: Sent message no 0
Socket 1 received msg: Sent message no 1
Socket 1 received msg: Sent message no 2
Socket 1 received msg: Sent message no 3
Socket 1 received msg: Sent message no 4

In order to use multiple clients, just create anew Java project and copy-paste the code of the client, but change the output to Socket 2 instead of Socket 1. You will see that when the server runs, the messages will be sent to both clients, and both clients will print the same results (except for the socket number part). Take a look at this screenshot here. We are running the first client through eclipse, the second through the command line, and the server through the command line as well.

Running a server and 2 clients.
Running a server and 2 clients.

3. Download the project

This was an example of MulticastSocket usage in Java.

Download
You can download the full source code of this example here : MulticastSocketServerMulticastSocketClient

Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
REIDAESTG
REIDAESTG
7 years ago

Oh Rei, you have to reset the buf on the client in order to achieve a proper result.

Foteini
Foteini
6 years ago

If i want to run the server on host1 and the client to 5 clients clientHost1, clientHost2 etc ?

Júnior
Júnior
5 years ago

Code of the project I’m using is yours.
For some reason the virtual machine does not receive the messages.
Do I need to set something up? Firewall? …
You have video in Youtube?

Back to top button