Hey guys. I have a bit of trouble with java multicast. The problem is that the receiving program never reveives anything. It just blocks on multicastSocket.receive(packet). The code below is just an example I found. So it should work. But it doesn't for me. Anyone know why it might block on receive(), even though packets is sent.
Any help is appreciated.
Multicast Send
Code:
// Which port should we send to
int port = 5000;
// Which address
String group = "225.4.5.6";
// Create the socket but we don't bind it as we are only going to send data
MulticastSocket s = new MulticastSocket();
// Note that we don't have to join the multicast group if we are only
// sending data and not receiving
// Fill the buffer with some data
byte buf[] = new byte[10];
for (int i=0; i<buf.length; i++) buf[i] = (byte)i;
// Create a DatagramPacket
DatagramPacket pack = new DatagramPacket(buf, buf.length,
InetAddress.getByName(group), port);
s.send(pack);
System.out.println("packet sent");
// And when we have finished sending data close the socket
s.close();
Multicast receive
Code:
// Which port should we listen to
int port = 5000;
// Which address
String group = "225.4.5.6";
// Create the socket and bind it to port 'port'.
MulticastSocket s = new MulticastSocket(port);
// join the multicast group
s.joinGroup(InetAddress.getByName(group));
// Now the socket is set up and we are ready to receive packets
// Create a DatagramPacket and do a receive
byte buf[] = new byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
System.out.println("Before receive");
s.receive(pack);
// it never reaches here
System.out.println("Received data from: " + pack.getAddress().toString() +
":" + pack.getPort() + " with length: " +
pack.getLength());
System.out.write(pack.getData(),0,pack.getLength());
System.out.println();
// close the socket
s.leaveGroup(InetAddress.getByName(group));
s.close();