我正在尝试编写每 10 秒向多播组发送一条消息的服务。发件人如下:
public void send(){
int port = (Integer) config.getValue("MULTICAST_PORT");
MulticastSocket users = new MulticastSocket(port);
users.setTimeToLive((Integer) config.getValue("MULTICAST_TTL"));
users.setLoopbackMode(false);
InetAddress multicastGroup = InetAddress.getByName((String) config.getValue("MULTICAST_IP"));
String x = "0";
DatagramPacket pkt = new DatagramPacket(x.getBytes(), x.getBytes().length, multicastGroup, port);
while(true) {
System.out.println("Send Pkt");
users.send(pkt);
Thread.sleep(10000);
}
}
接收方必须读取数据包并回复。
MulticastSocket multiServer = new MulticastSocket((Integer) config.getValue("MULTICAST_PORT"));
InetAddress multicastGroup = InetAddress.getByName((String) config.getValue("MULTICAST_IP"));
multiServer.joinGroup(multicastGroup);
while(true){
System.out.println("WAIT KeepAlive Packet");
server.receive(pkt);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
pkt.getData(), pkt.getOffset(), pkt.getLength()
));
if(in.readInt() == 0){ //0 means "OK"
ObjectSocket skt = new ObjectSocket(InetAddress.getByName(
(String) config.getValue("SERVER_HOSTNAME")),
Integer.parseInt((String) config.getValue("SERVER_PORT")));
try{
skt.writeObject(new PacketMessage(new SimpleMessage((String) config.getValue("USER"), (String) config.getValue("OAUTH")), PacketMessage.MessageType.KEEPALIVE));
} catch (UnregisteredConfigNameException e){
return;
}
}
对于发件人,输出是:
send Pkt
[10 sec sleep]
发送 Pkt
(很多次...)
对于接收器是:
等待 KeepAlive 数据包
这两个功能都在同一台机器上运行,使用两个不同的进程。MULTICAST_IP 相同(已验证)。我不明白为什么receive()
不返回。
MULTICAST_PORT 值在执行函数的引用方面有所不同,但这应该不是问题。不抛出异常。