有个问题困扰我很久了。 那是当我使用 netty 循环 writeAndFlush 将 DatagramPacket 发送到我的 udp 服务器时,大多数消息都会丢失。 但如果我让线程 hibernate 一段时间,所有消息都会被传递。 像这样:
public static void main(String[] args) throws InterruptedException {
int count = 3000;
AtomicInteger integer = new AtomicInteger(count);
AtomicInteger countInteger = new AtomicInteger();
Bootstrap bootstrap = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
ChannelFuture channelFuture = bootstrap.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_RCVBUF, 1024 * 1024)
.option(ChannelOption.SO_SNDBUF, 1024 * 1024)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new WakeupMessageEncoder())
.addLast(new WakeupMessageReplyDecoder())
.addLast(new SimpleChannelInboundHandler<WakeupMessageReply>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, WakeupMessageReply reply) throws Exception {
countInteger.getAndIncrement();
System.out.println(reply);
}
})
;
}
}).bind(0).sync();
Channel channel = channelFuture.channel();
long s = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
//TimeUnit.NANOSECONDS.sleep(1);
WakeupMessage message = new WakeupMessage(UUID.randomUUID().toString(), "192.168.0.3:12000", "89860918700328360182", "test message" + i);
channel.writeAndFlush(message).addListener(f -> integer.decrementAndGet());
}
while (true) {
if (integer.get() <= 0) {
break;
}
}
try {
channel.closeFuture();
System.out.println("done:" + (System.currentTimeMillis() - s) + "ms");
System.out.println(countInteger);
}finally {
group.shutdownGracefully();
}
}
我发送了 3000 条消息,但只收到很少... 像这样: 1744 messages 但如果我像这样 hibernate 线程:
for (int i = 0; i < count; i++) {
TimeUnit.NANOSECONDS.sleep(1);
WakeupMessage message = new WakeupMessage(UUID.randomUUID().toString(), "192.168.0.3:12000", "89860918700328360182", "test message" + i);
channel.writeAndFlush(message).addListener(f -> integer.decrementAndGet());
}
我将从udp服务器接收所有重播。
那为什么我必须 sleep 线程???
最佳答案
数据报数据包 (UDP) 无法保证传送,如果发送速度太快,可能会被丢弃。造成这种情况的可能原因有很多,在您的情况下,您很可能填满了发送缓冲区或接收缓冲区或两者。 This文章有更详细的介绍。
关于java - 为什么使用netty循环writeAndFlush发送DatagramPacket必须让线程 hibernate 一段时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771114/