gpt4 book ai didi

java - Eclipse 和多播数据包的奇怪/无法解释的行为

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:37 25 4
gpt4 key购买 nike

我的行为与描述非常相似here :

  • 在 Mac Book Pro、Snow Leopard 上运行
  • 使用多播套接字在本地主机上发送和接收数据包

我正在使用 Eclipse,当客户端/服务器从工作区启动时观察到以下行为:

  • 如果无线接口(interface)(机场)已启动并正在运行,客户端不会接收任何数据包
  • 如果界面关闭,一切都会按预期运行

但我不明白的是:

  • 如果我创建一个 JAR 并在任何控制台中运行代码 -> 一切都好!只是 Eclipse 似乎不喜欢机场;-)
  • 根据我连接的无线网络,上述行为可能会发生变化,即如果启用了机场(例如@ Uni),它也可以工作

有人对此有什么想法吗?

干杯

下面是服务器/客户端的简单代码:

@Override
public void run() {
String multicastAddress = "224.0.0.2";
int multicastPort = 8000;
MulticastSocket socket = null;
try {
try {
InetAddress multicastGoup = InetAddress.getByName(multicastAddress);
socket = new MulticastSocket(multicastPort);
socket.joinGroup(multicastGoup);
} catch (IOException e) {
e.printStackTrace();
return;
}
byte[] buffer = new byte[1024];

while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("BEFORE RECEIVE: listening on " + multicastAddress + ":" + multicastPort);
socket.receive(packet);
System.out.println("PACKET RECEIVED");

System.err.println("Client received: " + new String(packet.getData()));
}

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}

}

服务器:

    public void run() {
MulticastSocket socket = null;
try {
String multicastAddress = "224.0.0.2";
int multicastPort = 8000;
InetAddress multicastGoup = InetAddress.getByName(multicastAddress );
socket = new MulticastSocket(multicastPort);
socket.joinGroup(multicastGoup);

byte[] data = new String("Teststring").getBytes();

while (true) {
socket.send(new DatagramPacket(data, data.length, multicastGoup, multicastPort));
System.out.println("SERVER: Datagram sent");
Thread.sleep(1000);
}

} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}

最佳答案

来自Class MulticastSocket :

void  joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
Joins the specified multicast group at the specified interface.

尝试使用特定的接口(interface),这样您的 joinGroup 就不会落入默认值 - 这可能会因可用、开放的接口(interface)或 Eclipse 设置而异。

joinGroup

public void joinGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
throws IOException

Joins the specified multicast group at the specified interface.

If there is a security manager, this method first calls its
checkMulticast method with the mcastaddr argument as its argument.

Parameters:
mcastaddr - is the multicast address to join
netIf - specifies the local interface to receive
multicast datagram packets,
-- here is the catch
or null to defer to the interface set by
setInterface(InetAddress) or
setNetworkInterface(NetworkInterface)

关于java - Eclipse 和多播数据包的奇怪/无法解释的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5401282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com