Reputation: 107
I am new to the area of computer networks so please bear with me. Below is the code I am using to broadcast datapacket over internet from the server but I do not know how to receive the broadcasted message at client side. Can anybody help me with that?
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();
}
}
Upvotes: 3
Views: 5349
Reputation: 167
i think this should help -
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
}
}
Upvotes: 0
Reputation: 2605
Your code sends a message to a port, but no one is there to receive it.
You need to create a socket listener to the same port (4000), before you send the message so that your socket listener receives the message.
See this post for example: sending and receiving UDP packets using Java?
Upvotes: 3