引入包:
1 2 3 4 5 6 | <!-- netty-all --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.42.Final</version> </dependency> |
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.oio.OioEventLoopGroup; import io.netty.channel.rxtx.RxtxChannel; import io.netty.channel.rxtx.RxtxChannelConfig; import io.netty.channel.rxtx.RxtxDeviceAddress; /** * @program: hub.admin_java * @description: * @author: zf * @create: 2020-06-22 14:15 **/ public class RxtxServer { public static RxtxChannel channel; public static void main(String[] args) { OioEventLoopGroup group = new OioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channelFactory(new ChannelFactory<RxtxChannel>(){ @Override public RxtxChannel newChannel() { return channel; } }).handler(new ChannelInitializer<RxtxChannel>() { @Override protected void initChannel(RxtxChannel ch) throws Exception { } }); channel = new RxtxChannel(); // 设置channel的基本属性,波特率,数据位 channel.config().setBaudrate(9600) .setDatabits(RxtxChannelConfig.Databits.DATABITS_8) .setParitybit(RxtxChannelConfig.Paritybit.NONE) .setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1); //串口地址 RxtxDeviceAddress com1 = new RxtxDeviceAddress("COM1"); ChannelFuture future = b.connect(com1).sync(); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); }finally { group.shutdownGracefully(); } } class RxtxClientHandler extends SimpleChannelInboundHandler<String> { @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush("AT\n"); } @Override public void channelRead0(ChannelHandlerContext ctx, String msg) { System.out.println(msg); ctx.writeAndFlush("AT\n"); } } /** * 发送数据 * @param hexString 字符串 */ public static void writeAndFlush(String hexString) { if(!channel.isActive() || !channel.isOpen() || !channel.isWritable()){ return; } byte[] bytes = ByteUtils.stringToByte(hexString, Charset.defaultCharset()); ByteBuf buffer = channel.alloc().buffer(); ByteBuf byteBuf = buffer.writeBytes(bytes); channel.writeAndFlush(byteBuf).addListener((ChannelFutureListener) future -> { StringBuilder sb = new StringBuilder(); if (future.isSuccess()) { System.out.println(sb.toString() + "回写成功"); } else { System.out.println(sb.toString() + "回写失败"); } }); } } |
最后去RXTX的官网下载对应包:
注意如果是windows 版本2.2 2.1的没有64位版本的
这里有个windows64位 其他版本自行下载(下载地址http://fizzed.com/oss/rxtx-for-java)
- Copy
rxtxParallel.dll to (你的jdk文件目录 )\jre\bin\ - Copy
rxtxSerial.dll to (你的jdk文件目录 )\jre\bin\ - Copy
RXTXcomm.jar to (你的jdk文件目录 )\jre\lib\ext\
就可以顺利使用了。
串口模拟工具+windows64 RXTX https://pan.baidu.com/s/1-m9e8jKsgB4bV1ALSWF2jA 暗号:td2h
持续更新。。。