A brief explanation of Java Socket network programming multicast and broadcast implementation

  • 2020-04-01 04:37:22
  • OfStack

In Java, there are many ways to send and receive data. Some methods are closer to the bottom, and some problems need to be solved by the programmer, while others are more abstract and can be easily used. According to the level of abstraction, these methods of processing data are as follows:

1. Manual coding: use bit operations to code and parse one by one.

2. Use streams to code automatically: combine OutputStream and ByteArrayOutputStream.

3. Serialization: put the data into a data object, directly serialize the object and send it.
It's easy to use, but be aware of the loss of efficiency and that the recipient also USES Java.

4.RMI: sends all calls to methods, directly implementing remote calls to methods.


In method 1 at the bottom, we need to solve some of the bottom problems ourselves:

1. Integer sending: consider whether the end is large or small, unsigned or signed integer.

2. String sending: consider encoding.

3. Type without length limit, such as large integer: to be encoded as Frame, by delimiter or length bit
To distinguish between frames.

Multicasting and broadcasting

We can unicast a copy of the data to each recipient, but doing so can be very inefficient.
Only UDP sockets allow broadcasting and multicasting, with the difference that the broadcast is sent to all available on the network
Host, some operating systems may not allow ordinary users to broadcast operations; Multicast is only sent to those interested
The host. Specifically, the host that calls the MulticastSocket joinGroup() to join the multicast group.


public class MulticastReceiverTest {

 public static void main(String[] args) throws Exception {
 
 final InetAddress address = InetAddress.getByName("224.1.1.1");
 final int port = 45599;

 for (int i = 0; i < 5; i++) {
  new Thread("Thread #" + i){
  @Override
  public void run() {
   try {
   MulticastSocket sock = new MulticastSocket(port);
   sock.joinGroup(address);
   
   byte[] msg = new byte[256];
   DatagramPacket packet = new DatagramPacket(msg, msg.length);
   
   sock.receive(packet);
   System.out.println(Thread.currentThread().getName() + 
    " receive: " + new String(packet.getData()));
   } 
   catch (IOException e) {
   e.printStackTrace();
   }
  }
  }.start();
 }
 
 Thread.sleep(2000);
 
 MulticastSocket sock = new MulticastSocket();
 sock.setTimeToLive(32);
 
 byte[] msg = "hellomulticast".getBytes();
 DatagramPacket packet = new DatagramPacket(msg, msg.length, address, port);
 
 sock.send(packet);
 System.out.println("Message sent");
 }

}


Related articles: