在Linux中使用Java Netty时,多播发布数据包不起作用
我正在用Netty编写一个多播发送器。我在Linux中使用“ngrep”嗅探端口,但我看不到数据包。。。我检查了示例和代码,但我不明白为什么它不起作用。你知道我的代码有什么问题吗?在Linux中使用Java Netty时,多播发布数据包不起作用,linux,netty,multicast,Linux,Netty,Multicast,我正在用Netty编写一个多播发送器。我在Linux中使用“ngrep”嗅探端口,但我看不到数据包。。。我检查了示例和代码,但我不明白为什么它不起作用。你知道我的代码有什么问题吗? 谢谢 以下是我的代码: 出版商 public class Publisher implements Runnable { private InetSocketAddress groupAddress; private NioDatagramChannel ch; private AtomicLong se
谢谢 以下是我的代码: 出版商
public class Publisher implements Runnable {
private InetSocketAddress groupAddress;
private NioDatagramChannel ch;
private AtomicLong sequenceNumber = new AtomicLong(1);
public Publisher(InetSocketAddress address) throws InterruptedException {
groupAddress = address;
}
@Override
public void run() {
EventLoopGroup group = new NioEventLoopGroup();
try {
NetworkInterface ni = NetworkInterface.getByName("wlp3s0");
Enumeration<InetAddress> addresses = ni.getInetAddresses();
InetAddress localAddress = null;
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address instanceof Inet4Address) {
localAddress = address;
}
}
Bootstrap b =
new Bootstrap().group(group).channelFactory(new ChannelFactory<NioDatagramChannel>() {
@Override
public NioDatagramChannel newChannel() {
return new NioDatagramChannel(InternetProtocolFamily.IPv4);
}
})
.handler(new LoggingHandler(LogLevel.DEBUG))
.localAddress(localAddress, groupAddress.getPort())
.option(ChannelOption.IP_MULTICAST_IF, ni)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new MessageEncoder(groupAddress));
ch = (NioDatagramChannel) b.bind(groupAddress.getPort()).sync().channel();
ch.joinGroup(groupAddress, ni).sync();
ch.closeFuture().await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
public void publish(List<Message> messages) throws Exception {
ByteBuffer buffer = Packet.build(sequenceNumber.longValue(), messages);
if (buffer != null)
ch.writeAndFlush(buffer.array());
}
}
public class MessageEncoder extends MessageToMessageEncoder<Message> {
private final InetSocketAddress remoteAddress;
public MessageEncoder(InetSocketAddress remoteAddress) {
this.remoteAddress = remoteAddress;
}
@Override
protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
ByteBuffer b = msg.encode();
ByteBuf buffer = ctx.alloc().buffer(b.array().length);
out.add(new DatagramPacket(buffer, remoteAddress));
}
}
嗅探
$ sudo ngrep -d any port 21102
$ sudo ngrep -d any port 21102