如何从 Android 广播 UDP 数据包?

我需要使用 UDP 从我的 Android 应用程序向我的网络(以太网)上的每个设备广播一条消息。我不知道如何做到这一点,因为似乎没有任何关于如何发送广播消息的文档,只有关于如何使用 IP 地址发送到特定客户端的文档。

谢谢

stack overflow How to broadcast a UDP packet from Android?
原文答案

答案:

作者头像

这是一个有用的文档: google-AdroidUDP ,这是一个示例代码:

发件人:

 public void sendBroadcast(String messageStr) {
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

     try {
         DatagramSocket socket = new DatagramSocket();
         socket.setBroadcast(true);
         byte[] sendData = messageStr.getBytes();
         DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, getBroadcastAddress(), Constants.PORT);
         socket.send(sendPacket);
         System.out.println(getClass().getName() + "Broadcast packet sent to: " + getBroadcastAddress().getHostAddress());
     } catch (IOException e) {
         Log.e(TAG, "IOException: " + e.getMessage());
     }
 }

 InetAddress getBroadcastAddress() throws IOException {
     WifiManager wifi = (WifiManager)    
     mContext.getSystemService(Context.WIFI_SERVICE);
     DhcpInfo dhcp = wifi.getDhcpInfo();

     int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
     byte[] quads = new byte[4];
     for (int k = 0; k < 4; k++)
         quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
     return InetAddress.getByAddress(quads);
 }

接收者

      try {
          socket = new DatagramSocket(Constants.PORT, InetAddress.getByName("0.0.0.0"));
          socket.setBroadcast(true);

          while (true) {
              Log.i(TAG,"Ready to receive broadcast packets!");

              byte[] recvBuf = new byte[15000];
              DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
              socket.receive(packet);

              Log.i(TAG, "Packet received from: " + packet.getAddress().getHostAddress());
              String data = new String(packet.getData()).trim();
              Log.i(TAG, "Packet received; data: " + data);

              Intent localIntent = new Intent(Constants.BROADCAST_ACTION)
                  .putExtra(Constants.EXTENDED_DATA_STATUS, data);
              LocalBroadcastManager
                  .getInstance(this)
                  .sendBroadcast(localIntent);
          }
      }  catch (IOException ex) {
          Log.i(TAG, "Oops" + ex.getMessage());
      }