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