如何在 java 中接收广播消息

How to receive Broadcast message in java

我是计算机网络领域的新手,请多多包涵。下面是我用来从服务器通过互联网广播数据包的代码,但我不知道如何在客户端接收广播消息。有人可以帮我吗?

import java.net.*;
import java.io.*;

public class broadcast_message {
    private static DatagramSocket socket = null;

    public static void main(String[] args) throws IOException {
        broadcast("Hello", InetAddress.getByName("255.255.255.255"));
        System.out.println("Sent");
    }

    public static void broadcast(String broadcastMessage, InetAddress address) throws IOException {
        socket = new DatagramSocket();
        socket.setBroadcast(true);

        byte[] buffer = broadcastMessage.getBytes();

        DatagramPacket packet 
          = new DatagramPacket(buffer, buffer.length, address, 4000);
        socket.send(packet);
        socket.close();
    }
}

您的代码向端口发送了一条消息,但没有人在那里接收它。

您需要在同一端口 (4000) 上创建一个套接字侦听器,然后再发送消息,以便您的套接字侦听器接收消息。

参见这个 post 例如:sending and receiving UDP packets using Java?

我认为这应该有所帮助 -

package com.AK_Tech.MyBroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //your code    
}
}