有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么使用netty循环writeAndFlush发送数据包必须让线程休眠一段时间?

有一个问题让我困惑了很久。 也就是说,当我使用netty loop writeAndFlush将数据包发送到udp服务器时,大多数消息都会丢失。 但是如果我在线程中休眠一段时间,所有消息都会被传递。 像这样:

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 但是如果我像这样睡觉:

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服务器接收所有重播

那我为什么一定要睡觉呢


共 (2) 个答案

  1. # 1 楼答案

    数据报数据包(UDP)无法保证传输,如果发送速度过快,可能会被丢弃。有很多可能的原因,在您的情况下,您很可能正在填充发送缓冲区或接收缓冲区或两者This这篇文章更详细

  2. # 2 楼答案

    另一个选项是在写入和刷新时sync()侦听器,即

    channel.writeAndFlush(message).addListener(f -> integer.decrementAndGet()).sync();
    

    在我的测试中,这会得到所有3000个响应,所用的时间比睡觉要短得多。对于笔记本电脑上的本地UDP回显服务器:

    • 睡眠总时间:3758ms
    • 同步运行的总时间:407ms

    然而,正如@ewramner所指出的,任何选项都不能保证您将获得全部3000个响应