共同学习Netty源代码--ByteBuf(一)

Java NIO的API中最重要的三个接口是Selector、Channel和Buffer,其中Selector就像公交车调度管理者、Channel就像公交车、Buffer就像公交车上的座位,而数据就像乘客在这三个的协同作用下进行传输。

Netty封装了自己的buffer,也就是ByteBuf抽象类,先来看这个类。

public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf>

这个抽象类实现了ReferenceCounted接口和Comparable接口,后者不必多说,前者我查了一下资料,说是Netty4开始,相关对象的生命周期不再由垃圾回收器管理,而是由这个接口的实现类管理,来改进分配内存和释放内存的性能。从字面意义来看,这个接口的含义是引用计数,我的理解是,堆内存里的对象在栈内存中有多少引用。

这个接口定义了几个方法:

    int refCnt();

返回引用数,如果为0,则表示该对象没有引用了。

    ReferenceCounted retain();

这个方法用来增加一个引用计数器。

    ReferenceCounted retain(int increment);

这个方法用来增加指定个引用计数器。

    ReferenceCounted touch();

这个方法记录了当前可访问的位置,现在还不懂这个位置是什么。

    ReferenceCounted touch(Object hint);

这个方法和上面一样,但是传入了一些备用信息。

    boolean release();

这个方法用来减少一个引用计数器。

    boolean release(int decrement);

这个方法用来减少若干个引用计数器。

如果引用计数器减少到0,那么这个对象就会被收回。

现在回来看ByteBuf类。

public abstract int capacity();

这个抽象方法用来返回这个缓冲区可以承载多少字节的数据。

public abstract ByteBuf capacity(int newCapacity);

这个抽象方法用来替换当前这个缓冲区的容量,如果参数容量小于当前容量,则会砍掉一部分当前容量中的数据,反之会增加一些未被占有的容量。

public abstract int maxCapacity();

这个方法返回这个缓冲区最大的容量。

public abstract ByteBufAllocator alloc();

这个抽象方法返回分配这个缓冲区的ByteBufAllocator,也就是缓冲区分配器。 

public abstract ByteOrder order();

这个方法返回这个缓冲区的字节顺序。

public abstract ByteBuf order(ByteOrder endianness);

这个方法返回一个按照参数字节排序方式排序的ByteBuf。

public abstract ByteBuf unwrap();

如果这个缓冲区包裹了别的缓冲区,则返回被包裹的缓冲区,否则返回空。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Netty框架下的MODBUS-RTU协议的Java代码示例: ```java import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class ModbusRtuClient { private static final String HOST = "127.0.0.1"; private static final int PORT = 502; public static void main(String[] args) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<NioSocketChannel>() { @Override protected void initChannel(NioSocketChannel ch) { ch.pipeline() .addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[]{0x0d, 0x0a}))) .addLast(new StringDecoder(CharsetUtil.UTF_8)) .addLast(new ModbusRtuEncoder()) .addLast(new ModbusRtuClientHandler()); } }); try { ChannelFuture future = bootstrap.connect(HOST, PORT).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { bootstrap.group().shutdownGracefully(); } } private static class ModbusRtuEncoder extends MessageToByteEncoder<String> { @Override protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) { byte[] data = msg.getBytes(CharsetUtil.UTF_8); byte[] message = new byte[data.length + 2]; System.arraycopy(data, 0, message, 0, data.length); int crc = calculateCRC(message, message.length - 2); message[message.length - 2] = (byte) (crc & 0xff); message[message.length - 1] = (byte) ((crc >> 8) & 0xff); out.writeBytes(message); } private int calculateCRC(byte[] data, int length) { int crc = 0xffff; for (int i = 0; i < length; i++) { crc ^= data[i] & 0xff; for (int j = 0; j < 8; j++) { if ((crc & 0x0001) != 0) { crc >>= 1; crc ^= 0xA001; } else { crc >>= 1; } } } return crc; } } private static class ModbusRtuClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { System.out.println("Received response: " + msg); } @Override public void channelActive(ChannelHandlerContext ctx) { String request = "01 03 00 00 00 02 C4 0B"; System.out.println("Send request: " + request); ctx.writeAndFlush(request + "\r\n"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } } ``` 该代码实现了一个简单的MODBUS-RTU客户端,使用Netty框架进行网络通信,涉及到了编码器、解码器、帧分隔符、CRC校验等操作。请根据实际需求自行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值