Use of Java UDP broadcast and multicast -- Series 1

Posted by yuws on Fri, 25 Feb 2022 03:39:18 +0100

1.UDP broadcast.
The client opens a port to listen to data. The server specifies the port to send data, and the client can receive the data. The broadcast address bound by the server is 255.255.255.255

Client listening:

public class BroadcastClient {
    private int MessageIndex = 0;
    private int port = 6787;//Data listening binding port
    private boolean closed = false;


    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("BroadcastClient start ");
                runClient();
            }
        }).start();
    }

    DatagramSocket socket = null;

    private void runClient() {
        try {
            byte[] receiveBuffer = new byte[1024];//Data buffer
            socket = new DatagramSocket(port);//Bind ports for data listening
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);//Data receiving capsule
            while (!closed) {
                count();//Count the number and close the connection more than 50 times
                socket.receive(receivePacket);//receive data 
                System.out.println("received packet from " + receivePacket.getAddress().getHostAddress() + " : " + receivePacket.getPort());
                String msg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
                System.out.println("received " + msg);
                Thread.sleep(2000);
            }
            System.out.println("socket close ");
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void count() {
        MessageIndex++;
        if (MessageIndex >= 50) {
            closed = true;
        }
    }


    public static void main(String[] s) {
        BroadcastClient client = new BroadcastClient();
        client.start();
    }
}

//Operation effect

BroadcastClient start 
received packet from 192.168.2.221 : 58458
received hello ,message from server,0
received packet from 192.168.2.221 : 58460
received hello ,message from server,1
received packet from 192.168.2.221 : 58462
received hello ,message from server,2
received packet from 192.168.2.221 : 58464



Data sent by the server:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpBroadcastServer {
	public boolean closed = false;
	public String ip = "255.255.255.255";//Broadcast address
	public int port = 6787;//Specify broadcast receiving data port
	public int MessageIndex = 0;//Data transmission times

	public void start(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("UdpBroadcastServer start ");
				runServer();
			}
		}).start();
	}

	private void runServer(){
		try {
			while(!closed){  
				Thread.sleep(2000);
				send();
			}
		} catch (Exception e) {	
			e.printStackTrace();
			System.out.println("UdpTestServer run Exception: "+e.toString());  
		}  
	}

	public void send(){
		try{ 
			String sendMessage="hello ,message from server,"+MessageIndex++;   
			InetAddress adds = InetAddress.getByName(ip);
			DatagramSocket ds = new DatagramSocket();
			DatagramPacket dp = new DatagramPacket(sendMessage.getBytes(),sendMessage.length(), adds, port);
			ds.send(dp);
			ds.close();
		}catch (Exception e) {
			System.out.println("UdpTestServer send Exception: "+e.toString());  
		}

		if(MessageIndex>=50){
			closed = true;
			System.out.println("closed  ");  
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UdpBroadcastServer server = new UdpBroadcastServer();
		server.start();
	}

}
//Operation effect
UdpBroadcastServer start 
closed  

2.UDP multicast
Multicast needs to add a multicast address and a specific port to receive data
1. The multicast ip added is different and cannot receive multicast
2. The added multicast ip is the same, but the multicast port is different, so the multicast cannot be received
3. Like the multicast ip and the multicast port, you can receive the sent multicast data, even if you send the data yourself
client:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * Multicast needs to add a multicast address and a specific port to receive data
 * 1.Multicast is not the same as ip
 * 2.The added multicast ip is the same, but the multicast port is different, so the multicast cannot be received
 * 3.Like multicast ip and multicast port, you can receive the multicast data sent, even if you send the data yourself
 */

public class UpdGroupClient {
    private int MessageIndex = 0;
    private String ip = "224.0.0.1";//Multicast address
    private int port = 6789;//Specify the data receiving port
    private boolean closed = false;

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("UpdGroupClient start ");
                runClient();
            }
        }).start();
    }

    MulticastSocket socket = null;

    public void runClient() {
        try {
            byte[] receiveBuffer = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
            InetAddress group = InetAddress.getByName(ip);
            socket = new MulticastSocket(port);
            socket.joinGroup(group);//Join multicast address
            while (!closed) {
                send();
                socket.receive(receivePacket);
                System.out.println("received packet from " + receivePacket.getAddress().getHostAddress() + " : " + receivePacket.getPort());
                String msg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
                System.out.println("received " + msg);
                Thread.sleep(2000);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Multicast sending data
     */
    public void send() {
        String msg = "message from client," + MessageIndex++;
        try {
            byte[] message = msg.getBytes(); //Send message
            InetAddress inetAddress = InetAddress.getByName(ip); //Specify multicast address
            DatagramPacket datagramPacket = new DatagramPacket(message, message.length, inetAddress, port); //Send data packet
            MulticastSocket multicastSocket = new MulticastSocket();//Create multicast socket
            multicastSocket.send(datagramPacket);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (MessageIndex >= 50) {
            closed = true;
        }
    }


    public static void main(String[] s) {
        UpdGroupClient client = new UpdGroupClient();
        client.start();
    }
}


//Operation effect
UpdGroupClient start 
UpdGroupClient start 
received packet from 192.168.2.221 : 57242
received message from client,0
received packet from 192.168.2.221 : 57244
received message from client,1
received packet from 192.168.2.221 : 57245
received hello ,message from server,0
received packet from 192.168.2.221 : 57247
received message from client,2
received packet from 192.168.2.221 : 57248
received hello ,message from server,1
received packet from 192.168.2.221 : 57249
received message from client,3
received packet from 192.168.2.221 : 57250
received hello ,message from server,2
received packet from 192.168.2.221 : 51521
received message from client,4
received packet from 192.168.2.221 : 51522
received hello ,message from server,3
received packet from 192.168.2.221 : 51523
received message from client,5
received packet from 192.168.2.221 : 51524
received hello ,message from server,4
received packet from 192.168.2.221 : 63331
received message from client,6
received packet from 192.168.2.221 : 63332
received hello ,message from server,5
received packet from 192.168.2.221 : 63333

Server side:

public class UdpGroupServer {
	public boolean closed = false;
	public String ip = "224.0.0.1";//Multicast virtual address
	public int port = 6789;//Multicast Ip
	public int MessageIndex = 0;

	public void start(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("UdpTestServer start ");
				runServer();
			}
		}).start();
	}

	private void runServer(){
		try {
			InetAddress	group = InetAddress.getByName(ip);
			MulticastSocket s = new MulticastSocket(port);   
			byte[] arb = new byte[1024];  
			s.joinGroup(group);//Join this group  
			while(!closed){  
				DatagramPacket datagramPacket =new DatagramPacket(arb,arb.length);  
				s.receive(datagramPacket);  
				System.out.println("received packet from " + datagramPacket.getAddress().getHostAddress() + " : " + datagramPacket.getPort());		
				System.out.println(new String(arb)); 
				Thread.sleep(2000);
				send();
			}
		} catch (Exception e) {	
			e.printStackTrace();
			System.out.println("UdpTestServer run Exception: "+e.toString());  
		}  
	}




	public void send(){
		try{ 
			String sendMessage="hello ,message from server,"+MessageIndex++;  
			byte[] message = sendMessage.getBytes(); //Send message
			InetAddress inetAddress = InetAddress.getByName(ip); //Specify multicast address
			DatagramPacket datagramPacket = new DatagramPacket(message, message.length, inetAddress, port); //Send data packet
			MulticastSocket multicastSocket = new MulticastSocket();//Create multicast socket
			multicastSocket.send(datagramPacket);
		}catch (Exception e) {
			System.out.println("UdpTestServer send Exception: "+e.toString());  
		}

		if(MessageIndex>=50){
			closed = true;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		UdpGroupServer server = new UdpGroupServer();
		server.start();
	}

}
//Operation effect

UdpTestServer start 
received packet from 192.168.2.221 : 57242
message from client,0
received packet from 192.168.2.221 : 57245
hello ,message from server,0
received packet from 192.168.2.221 : 57248
hello ,message from server,1

Multicast address:
Multicast groups can be permanent or temporary. A part of the multicast group address is officially assigned, which is called a permanent multicast group. What keeps the permanent multicast group unchanged is its ip address, and the composition of members in the group can be changed. The number of members in a permanent multicast group can be arbitrary or even zero. ip multicast addresses that are not reserved for permanent multicast groups can be used by temporary multicast groups.

224.0.0.0 ~ 224.0.0.255 are reserved multicast addresses (permanent group addresses). Address 224.0.0.0 is reserved for allocation, and other addresses are used by routing protocols;

224.0.1.0 ~ 224.0.1.255 are public multicast addresses, which can be used for the Internet;

224.0.2.0 ~ 238.255.255.255 are multicast addresses (temporary group addresses) available to users, which are valid in the whole network;

239.0.0.0 ~ 239.255.255.255 are local management multicast addresses, which are only valid in a specific local range. Later, we may talk about the meaning of this address protocol.
The article is taken from the maple snow of Nan

Topics: Java server udp