【发布时间】:2018-10-31 22:11:35
【问题描述】:
我有一个示例,它使用 java 1.8 和 netty 4.1.30.Final 版本 IdleStateHandler 在 400 毫秒内未采取任何操作时输出当前时间。但是,当前时间是以 2 秒而不是 400 毫秒为间隔输出的。
这是我的示例代码
Client.java
public void connect() {
EventLoopGroup workerGroup = new OioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
.channel(RxtxChannel.class)
.option(RxtxChannelOption.BAUD_RATE, 38400)
.option(RxtxChannelOption.DATA_BITS, RxtxChannelConfig.Databits.DATABITS_8)
.option(RxtxChannelOption.PARITY_BIT, RxtxChannelConfig.Paritybit.NONE)
.option(RxtxChannelOption.STOP_BITS, RxtxChannelConfig.Stopbits.STOPBITS_1)
.handler(new ExampleChannelInitializer());
this.channel = bootstrap.connect(new RxtxDeviceAddress("COM1")).sync().channel();
this.channel.closeFuture().addListener(f -> {
workerGroup.shutdownGracefully();
});
} catch (Exception e) {
throw new ConnectionException(e.getMessage(), e);
}
}
ExampleChannelInitializer.java
@Override
protected void initChannel(RxtxChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new IdleStateHandler(0, 0, 400, TimeUnit.MILLISECONDS));
pipeline.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
System.out.println(LocalDateTime.now());
}
});
}
控制台
2018-10-30T10:42:02.762
2018-10-30T10:42:04.789
2018-10-30T10:42:06.818
2018-10-30T10:42:08.844
2018-10-30T10:42:10.871
【问题讨论】: