学习Netty以便通过串口读写数据

       最近在接触到Netty,以前都用的比较少。其实最近在项目中,发现很多地方都可以将Netty替代原来的Socket编程,应该在效率上会有改善。我也是先说下自己在项目中遇到的问题,去学习Netty.

    由于项目中采用比较老的一个开源的框架,去读写串口数据。RxTxcommon.jar可以通过这个开源的框架去读写串口数据。后来Netty4.1.5以后,也有这种实现方法。效率比以前更快。实现方法都相似。代码如下:

 group = new OioEventLoopGroup();        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
            .channelFactory(new ChannelFactory<RxtxChannel>() {
            	public RxtxChannel newChannel() {
            		return channel;
            	}
            })
            .handler(new ChannelInitializer<RxtxChannel>() {
                 @Override
                 public void initChannel(RxtxChannel ch) throws Exception {
                     ch.pipeline().addLast(
                    		 //outbound handler
                    		 new BytesEncoder(sequenceIdMgr),
                    		 //inbound handler
                    		 //new SerialDebugIncoming(),
                    		 new LengthFieldBasedFrameDecoder(AP_MSG_MAX_LENGTH,6,1,0,0,true),
                    		 new BytesDecoder(sequenceIdMgr),
                    		 rxtxClient
                     );
                 }
             });
            
            channel = new RxtxChannel();
            channel.config().setBaudrate(57600);
            future = b.connect(new RxtxDeviceAddress(serialport)).sync();
           
        } 
在代码里面,需要定义解析数据方法和加密方法。以便可以通过串口解析内容,加密内容下发到串口。特别需要注意的是。连接串口的时候需要定义波特率,在这里,如果没有看源代码,很多API中没有说明这个地方,在RxtxChannel这个类中,获取到channel,该对象中有属性对象RxtxChannelConfig,这个对象中,看源代码如下:

/**
     * Sets the baud rate (ie. bits per second) for communication with the serial device.
     * The baud rate will include bits for framing (in the form of stop bits and parity),
     * such that the effective data rate will be lower than this value.
     *
     * @param baudrate The baud rate (in bits per second)
     */
    RxtxChannelConfig setBaudrate(int baudrate);
     设置好波特率,然后通过方法连接,具体的读取和写入,下篇文章中说,谢谢!

猜你喜欢

转载自blog.csdn.net/yanchangyufan/article/details/77199326