List of usage examples for io.netty.buffer ByteBuf readerIndex
public abstract int readerIndex();
From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveRequestDecoder.java
License:Open Source License
private void checkSum(ByteBuf in, int wholeLength) { int crcGet = in.getUnsignedShort(in.readerIndex() + wholeLength - 2); int crcCalc = Utils.crc(in, in.readerIndex(), wholeLength - 2); if (crcCalc != crcGet) { throw new DecoderException("wrong crc"); }/*from w ww . ja va 2s.c om*/ }
From source file:net.epsilony.utils.codec.modbus.handler.ModbusSlaveResponseEncoderTest.java
License:Open Source License
@Test public void test() { ModbusSlaveResponseEncoder encoder = new ModbusSlaveResponseEncoder(); EmbeddedChannel channel = new EmbeddedChannel(encoder); ModbusResponse response = new ModbusResponse() { {/*from w w w .jav a2 s. c o m*/ transectionId = 0xabcd; unitId = 0x83; } @Override public void writePduCore(ByteBuf out) { out.writeShort(0xabcd); out.writeShort(0xcdef); transectionId++; } @Override public int getPduCoreLength() { return 4; } @Override public int getFunctionCode() { // TODO Auto-generated method stub return 6; } }; ByteBuf buf = null; for (int i = 0; i < 3; i++) { channel.writeOutbound(response); buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 3, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes()); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } encoder.setWithCheckSum(true); for (int i = 0; i < 3; i++) { channel.writeOutbound(response); } for (int i = 0; i < 3; i++) { buf = (ByteBuf) channel.readOutbound(); int[] buffer = new int[] { 0xab, 0xcd + i + 6, 0x00, 0x00, 0x00, 0x06, 0x83, 0x06, 0xab, 0xcd, 0xcd, 0xef }; assertEquals(buffer.length, buf.readableBytes() - 2); for (int b : buffer) { assertEquals(b, buf.readUnsignedByte()); } int calcCrc = Utils.crc(buf, buf.readerIndex() - buffer.length, buffer.length); assertEquals(calcCrc, buf.readUnsignedShort()); assertTrue(!buf.isReadable()); ReferenceCountUtil.release(buf); } }
From source file:net.NettyEngine4.ServerDecoder.java
License:Apache License
/** * decode message will be added the MessageList<Object> out queue! * @param ctx/*from www.j ava2 s . co m*/ * @param in read data * @param out ?? * @throws Exception * ?channel OutputMessageBuf? * I/O ? ???? */ @Override protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { //decode message to list if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes()); in.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; failIfNecessary(ctx, false); return; } if (in.readableBytes() < lengthFieldEndOffset) { return; } int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset; /**?? 124,???short 2*/ long frameLength = (in.order(byteOrder)).getUnsignedShort(actualLengthFieldOffset); if (frameLength < 0) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { in.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; tooLongFrameLength = frameLength; bytesToDiscard = frameLength - in.readableBytes(); in.skipBytes(in.readableBytes()); failIfNecessary(ctx, true); return; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (in.readableBytes() < frameLengthInt) { return; } if (initialBytesToStrip > frameLengthInt) { in.skipBytes(frameLengthInt); throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } //skip head in.skipBytes(initialBytesToStrip); // extract frame int readerIndex = in.readerIndex(); int actualFrameLength = frameLengthInt - initialBytesToStrip; //? ByteBuf frame = ctx.alloc().heapBuffer(actualFrameLength); //heap buffer frame.writeBytes(in, readerIndex, actualFrameLength); in.readerIndex(readerIndex + actualFrameLength); //set reader Index //decode message and add to list this is byteBuffer if (frame != null) { out.add(frame); } }
From source file:net.NettyEngine4.ServerHandler.java
License:Apache License
/** * Calls {@link io.netty.channel.ChannelHandlerContext#fireChannelRead(Object)} to forward * to the next {@link io.netty.channel.ChannelInboundHandler} in the {@link io.netty.channel.ChannelPipeline}. * ?channel RecyclableArrayListchannel? *///from w w w. ja v a2 s . co m @Override public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception { ByteBuf msg = (ByteBuf) message; /** * if channel inactive ,the finally callback method{@link io.netty.handler.codec.ByteToMessageDecoder#channelInactive(io.netty.channel.ChannelHandlerContext)} * this method will do some clear work ,if Recycle ArrayList is not empty ,so will invoke method channelRead,and release byteBuffer, * every task(byteBuffer data which was store blockingQueue will be executor by the "" ,no matter what it's status) , * so if the channel inactive ,we will clear some buf ,in case of memory crash application,like this : */ if (!ctx.channel().isActive()) { //inactive status , release buffer msg.release(); msg = null; } else { try { /**ID**/ int ID = msg.readInt(); /**byte[]pb?**/ int length = msg.readableBytes(); if (length != 0) { byte[] array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); msg.release(); //release byte buffer msg = null; //collection by GC directly MessageLite messageLite = IController.MESSAGE_LITE[ID].getParserForType().parseFrom(array, 0, length, ExtensionRegistryLite.getEmptyRegistry()); array = null; //collection by GC directly logger.debug("? &( ^___^ )& -->" + messageLite.toString() + "ID:" + ID); IController.GAME_CONTROLLERS[ID].DispatchMessageLit(messageLite, player); } else { msg.release(); msg = null; /**?null*/ IController.GAME_CONTROLLERS[ID].DispatchMessageLit(null, player); } } catch (UninitializedMessageException e) { e.printStackTrace(); } } }
From source file:net.sourceforge.entrainer.socket.PortUnificationHandler.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Will use the first five bytes to detect a protocol. if (in.readableBytes() < 5) { return;/* ww w . ja v a 2s. c o m*/ } final int magic1 = in.getUnsignedByte(in.readerIndex()); final int magic2 = in.getUnsignedByte(in.readerIndex() + 1); if (isHttp(magic1, magic2)) { switchToWebSockets(ctx); } else { switchToJava(ctx); } }
From source file:net.tomp2p.connection.DefaultSignatureFactory.java
License:Apache License
@Override public PublicKey decodePublicKey(ByteBuf buf) { if (buf.readableBytes() < 2) { return null; }/* w w w .j a v a 2 s. c o m*/ int len = buf.getUnsignedShort(buf.readerIndex()); if (buf.readableBytes() - 2 < len) { return null; } buf.skipBytes(2); if (len <= 0) { return PeerMaker.EMPTY_PUBLICKEY; } byte me[] = new byte[len]; buf.readBytes(me); return decodePublicKey(me); }
From source file:net.tomp2p.connection.DSASignatureFactory.java
License:Apache License
@Override public PublicKey decodePublicKey(ByteBuf buf) { if (buf.readableBytes() < 2) { return null; }/* w ww .java 2 s .c o m*/ int len = buf.getUnsignedShort(buf.readerIndex()); if (buf.readableBytes() - 2 < len) { return null; } buf.skipBytes(2); if (len <= 0) { return PeerBuilder.EMPTY_PUBLIC_KEY; } byte me[] = new byte[len]; buf.readBytes(me); return decodePublicKey(me); }
From source file:net.tomp2p.peers.PeerAddress.java
License:Apache License
/** * Creates a PeerAddress from a Netty ByteBuf. * // w ww .j a v a 2 s.co m * @param channelBuffer * The channel buffer to read from */ public PeerAddress(final ByteBuf channelBuffer) { // get the peer ID, this is independent of the type int readerIndex = channelBuffer.readerIndex(); // get the type final int options = channelBuffer.readUnsignedByte(); this.net6 = (options & NET6) > 0; this.firewalledUDP = (options & FIREWALL_UDP) > 0; this.firewalledTCP = (options & FIREWALL_TCP) > 0; this.relayed = (options & RELAYED) > 0; this.slow = (options & SLOW) > 0; this.portForwarding = (options & PORT_FORWARDING) > 0; final int relays = channelBuffer.readUnsignedByte(); // first: three bits are the size 1,2,4 // 000 means no relays // 001 means 1 relay // 010 means 2 relays // 011 means 3 relays // 100 means 4 relays // 101 means 5 relays // 110 is not used // 111 is not used // second: five bits indicate if IPv6 or IPv4 -> in total we can save 5 addresses this.relaySize = (relays >>> TYPE_BIT_SIZE) & MASK_07; final byte b = (byte) (relays & MASK_1F); this.relayType = Utils.createBitSet(b); // now comes the ID byte[] me = new byte[Number160.BYTE_ARRAY_SIZE]; channelBuffer.readBytes(me); this.peerId = new Number160(me); this.peerSocketAddress = PeerSocketAddress.create(channelBuffer, isIPv4()); if (relaySize > 0) { this.peerSocketAddresses = new ArrayList<PeerSocketAddress>(relaySize); for (int i = 0; i < relaySize; i++) { this.peerSocketAddresses.add(PeerSocketAddress.create(channelBuffer, !relayType.get(i))); } } else { this.peerSocketAddresses = EMPTY_PEER_SOCKET_ADDRESSES; } this.size = channelBuffer.readerIndex() - readerIndex; // not used here this.offset = -1; this.hashCode = peerId.hashCode(); }
From source file:net.tomp2p.peers.PeerSocketAddress.java
License:Apache License
/** * Decodes a PeerSocketAddress from a Netty buffer. * /*from www. ja va2 s. c o m*/ * @param buf * The Netty buffer * @param isIPv4 * Whether the address is IPv4 or IPv6 * @return the PeerSocketAddress and the new offset */ public static PeerSocketAddress create(final ByteBuf buf, final boolean isIPv4) { final int tcpPort = buf.readUnsignedShort(); final int udpPort = buf.readUnsignedShort(); final InetAddress address; final byte[] me; if (isIPv4) { me = new byte[Utils.IPV4_BYTES]; buf.readBytes(me); address = Utils.inet4FromBytes(me, 0); } else { me = new byte[Utils.IPV6_BYTES]; buf.readBytes(me); address = Utils.inet6FromBytes(me, 0); } return new PeerSocketAddress(address, tcpPort, udpPort, buf.readerIndex()); }
From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java
License:Apache License
@Override public AlternativeCompositeByteBuf setBytes(int index, ByteBuf src, int length) { checkIndex(index, length);/*from w w w .j a v a2s . c o m*/ if (src == null) { throw new NullPointerException("src"); } if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(String.format( "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); return this; }