I’m implementing multicast with Java, but I’ve encountered some issues. When I start with [Host A receiver -> Host B receiver -> Host A sender], Host B cannot receive the multicast messages. However, when I start with [Host B receiver -> Host A receiver -> Host A sender], Host B can receive the multicast messages. Host A and Host B are in the same LAN. What could be causing this?
Here is my receiver and sender code.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/**
* @author 肖嘉威 [email protected]
* @date 2024/4/23 11:33
*/
public class MulticastSender {
public static void main(String[] args) throws IOException {
InetAddress group = InetAddress.getByName("234.2.3.4");
int port = 12122;
MulticastSocket ms = null;
try {
ms = new MulticastSocket(port);
ms.joinGroup(group);
while (true) {
String message = "Hello " + new java.util.Date();
byte[] buffer = message.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, group, port);
ms.send(dp);
System.out.println("发送数据报给" + group + ":" + port);
Thread.sleep(2000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ms != null) {
try {
ms.leaveGroup(group);
ms.close();
} catch (IOException e) {
}
}
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
/**
* @author 肖嘉威 [email protected]
* @date 2024/4/23 11:34
*/
public class MulticastReceiver {
public static void main(String[] args) throws Exception {
InetAddress group = InetAddress.getByName("234.2.3.4");
int port = 12122;
MulticastSocket ms = null;
try {
ms = new MulticastSocket(port);
ms.joinGroup(group);
byte[] buffer = new byte[8192];
while (true) {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ms.receive(dp);
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println(s);
}
}catch (IOException e){
e.printStackTrace();
}finally
{
if (ms !=null)
{
try
{
ms.leaveGroup(group);
ms.close();
} catch (IOException e) { }
}
}
}
}
I used wireshark. This is the result of the first boot sequence
Host B
Host A
This is the result of the second boot sequence
Host B
Host A
5