这是我的示例代码
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
答案 0 :(得分:0)
不幸的是,这实际上是OIO传输以及RXTX如何在后台运行的问题。您可以使用RxtxChannelOption.READ_TIMEOUT
和RxtxChannelOption.WAIT_TIME
来使它们更“精确”,并将它们设置为较小的值。