我有一个例子,它使用 java 1.8 和 netty 4.1.30.Final 版本 IdleStateHandler 在 400 毫秒内没有采取任何行动时输出当前时间。但是,当前时间是以 2 秒而不是 400 毫秒为间隔输出的。
这是我的示例代码
客户端.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);
}
}
示例ChannelInitializer.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
幕布斯6054654
相关分类