如何在Java中接收广播消息

时间:2019-02-26 12:24:22

标签: java sockets network-programming broadcasting

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

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();
    }
}

2 个答案:

答案 0 :(得分:1)

您的代码将消息发送到端口,但是没有人可以接收它。

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

例如,请参阅此帖子:sending and receiving UDP packets using Java?

答案 1 :(得分:0)

我认为这应该会有所帮助 -

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    
}
}