我正在尝试通过互联网实现多播通信。这是我的代码
首先发送然后接收5次代码:
public static void main(String args[]) throws IOException
{
MulticastSocket socket = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("228.5.6.7");
socket.joinGroup(group);
socket.setNetworkInterface(NetworkInterface.getByInetAddress(group));
DatagramPacket packet;
System.out.println("Trasmitter Started!!");
for (int i = 0; i < 5; i++)
{
String buf = "Hi receiver";
packet = new DatagramPacket(buf.getBytes(), buf.getBytes().length,group,4446);
socket.send(packet);
System.out.println("Packet Sent!");
byte[] buff = new byte[256];
packet = new DatagramPacket(buff,buff.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
}
socket.leaveGroup(group);
socket.close();
}
仅接收:
public static void main(String args[]) throws IOException
{
System.setProperty("java.net.preferIPv4Stack", "true");
MulticastSocket socket = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("228.5.6.7");
//socket.setNetworkInterface(NetworkInterface.getByInetAddress(group));
socket.setInterface(group);
socket.joinGroup(group);
DatagramPacket packet;
System.out.println("Receiver Started!!");
for (int i = 0; i < 5; i++)
{
byte[] buff = new byte[256];
packet = new DatagramPacket(buff,buff.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("Received Message: " + received);
}
socket.leaveGroup(group);
socket.close();
}
代码在一台机器上工作但是当我尝试在另一台机器上运行接收器时,它没有收到任何东西。我没有得到我错的地方?我搜索了一些解决方案,他们说要将socketInterface添加到套接字,但这也不起作用
操作系统:Windows 8.1
我也在使用代理(如果这可能是问题)
答案 0 :(得分:0)
socket.setNetworkInterface(...);
摆脱这条线。您将接口设置为组地址,这没有意义。我很惊讶它没有抛出异常。