Android uses MulticastSocket to realize multicast pictures

  • 2021-10-27 08:58:48
  • OfStack

DatagramSocket only allows datagrams to be sent to specified destination addresses, while MulticastSocket can broadcast datagrams to multiple clients. The main idea is to set up a group of special network addresses as multicast addresses. Each multicast address is regarded as a group. When the client needs to send or receive broadcast messages, it can join the group.

The IP protocol provides these special IP addresses for multicast, and these IP addresses range from 224.0. 0.0 to 239.255. 255.255. When MulticastSocket sends one DatagramPacket to the multicast IP address, the data will be automatically broadcast to all MulticastSocket added to the address, and the MulticastSocket can also be set to receive the data sent by itself.

If it's just an MulticastSocket object for sending datagrams, use the default address, a random port. However, if an MulticastSocket object for reception is created, the MulticastSocket object must specify a port, otherwise the sender cannot determine the destination port for sending the datagram.

The following is a simple example to realize multicast pictures:

Tool classes for multicast:


public class ComUtil
{
 public static final String BROADCAST_IP = "224.2.2.2";
 public static final int BOADCAST_PORT = 30000;
 private static final int DATA_LEN = 100 * 1024;
 // Object that defines this program MulticastSocket Instances 
 private MulticastSocket socket = null;
 // Defining a broadcast IP Address 
 private InetAddress broadcastAddress = null;
 // Defines an array of characters to receive network data 
 byte[] inBuff = new byte[DATA_LEN];
 // Object to be accepted with the specified byte array DatagramPacket Object 
 private DatagramPacket inPacket = new DatagramPacket(inBuff , inBuff.length);
 // Definition 1 For sending DatagramPacket Object 
 private DatagramPacket outPacket = null;
 private Handler handler;

 // Constructor that initializes resources 
 public ComUtil(Handler handler) throws Exception
 {
 this.handler = handler;
 // Because the MultcastSocket Object needs to accept data, so there is a specified port 
 socket = new MulticastSocket(BOADCAST_PORT);
 broadcastAddress = InetAddress.getByName(BROADCAST_IP);
 // Set the socket Adds the specified multicast address 
 socket.joinGroup(broadcastAddress);
 // Set this MultcastSocket The sent datagram will be sent to itself 
 socket.setLoopbackMode(false);
 // For initializing transmission DatagramSocket Which contains 1 The length is 0 Byte array of 
 outPacket = new DatagramPacket(new byte[0] , 0 , broadcastAddress , BOADCAST_PORT);
 new ReadBroad().start();
 }

 // Tool method for broadcasting messages 
 public void broadCast(byte[] msg)
 {
 try
 {
  // Will msg String to byte array 
  byte[] buff = msg;
  // Set the for sending DatagramPacket Byte array in 
  outPacket.setData(buff);
  // Send data 
  socket.send(outPacket);
 }
 catch (IOException e)
 {
  e.printStackTrace();
 }
 }

 // Continuous read MulticastSocket Threads of 
 class ReadBroad extends Thread
 {
 public void run()
 {
  while (true)
  {
  try
  {
   // Read Socket Data in 
   socket.receive(inPacket);
   Message msg = new Message();
   msg.what = 0x123;
   msg.obj = inBuff;
   handler.sendMessage(msg);
  }
  catch (IOException e)
  {
   e.printStackTrace();
  }
  }
 }
 }
}

Class MainActivity:


public class MainActivity extends Activity
{
 private Button button;
 private ImageView img;
 private ComUtil comUitl;
 Handler handler = new Handler()
 {
 @Override
 public void handleMessage(Message msg)
 {
  if (msg.what == 0x123)
  {
  byte[] result = (byte[]) msg.obj;
  img.setImageBitmap(BitmapFactory.decodeByteArray(result , 0 , result.length));
  }
 }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main_activity);
 try
 {
  comUitl = new ComUtil(handler);
 }
 catch (Exception e)
 {
  e.printStackTrace();
 }

 button = (Button) findViewById(R.id.send_img_all);
 img = (ImageView) findViewById(R.id.receiver_img);
 button.setOnClickListener(new View.OnClickListener()
 {
  @Override
  public void onClick(View view)
  {
  sendData();
  }
 });
 }

 private void sendData()
 {
 Bitmap bitmap = BitmapFactory.decodeResource(getResources() , R.drawable.wenqing2);
 ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG , 100 , byteArray);
 bitmap.recycle();
 final byte[] msg = byteArray.toByteArray();
 new Thread()
 {
  @Override
  public void run()
  {
  comUitl.broadCast(msg);
  }
 }.start();

 try
 {
  byteArray.close();
 }
 catch (IOException e)
 {
  e.printStackTrace();
 }
 }
}

Related articles: