List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract ByteBuf readBytes(ByteBuffer dst);
From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoClientHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("Client received : " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes()))); msg.release();/*from w ww . j av a 2 s . c o m*/ }
From source file:com.flowpowered.engine.network.codec.ChunkDataCodec.java
License:MIT License
@Override public ChunkDataMessage decode(ByteBuf buffer) throws IOException { final byte info = buffer.readByte(); final boolean unload = (info & ISUNLOAD) == ISUNLOAD; final int x = buffer.readInt(); final int y = buffer.readInt(); final int z = buffer.readInt(); if (unload) { return new ChunkDataMessage(x, y, z); } else {/*w w w. j av a2 s . co m*/ int uncompressedSize = INTIAL_DATA_SIZE; final byte[] uncompressedData = new byte[uncompressedSize]; final byte[] compressedData = new byte[buffer.readInt()]; buffer.readBytes(compressedData); Inflater inflater = new Inflater(); inflater.setInput(compressedData); try { inflater.inflate(uncompressedData); } catch (DataFormatException e) { throw new IOException("Error while reading chunk (" + x + "," + y + "," + z + ")!", e); } inflater.end(); final int[] blocks = new int[Chunk.BLOCKS.VOLUME]; int index = 0; for (int i = 0; i < blocks.length; ++i) { blocks[i] = uncompressedData[index++] | (uncompressedData[index++] << 8) | (uncompressedData[index++] << 16) | (uncompressedData[index++] << 24); } if (index != uncompressedData.length) { throw new IllegalStateException( "Incorrect parse size - actual:" + index + " expected: " + uncompressedData.length); } return new ChunkDataMessage(x, y, z, blocks); } }
From source file:com.flowpowered.network.pipeline.MessageDecoder.java
License:MIT License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { Protocol protocol = messageHandler.getSession().getProtocol(); Codec<?> codec;/*from ww w . j a v a 2s . co m*/ try { codec = protocol.readHeader(buf); } catch (UnknownPacketException e) { // We want to catch this and read the length if possible int length = e.getLength(); if (length != -1 && length != 0) { buf.readBytes(length); } throw e; } if (codec == null) { throw new UnsupportedOperationException("Protocol#readHeader cannot return null!"); } Message decoded = codec.decode(buf); out.add(decoded); }
From source file:com.flowpowered.network.pipeline.MessageProcessorDecoder.java
License:MIT License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> frames) throws Exception { MessageProcessor processor = getProcessor(); if (processor == null) { frames.add(buf.readBytes(buf.readableBytes())); return;//w w w. j a va 2s . c om } // Eventually, we will run out of bytes and a ReplayableError will be called ByteBuf liveBuffer = ctx.alloc().buffer(); liveBuffer = processor.processInbound(ctx, buf, liveBuffer); frames.add(liveBuffer); }
From source file:com.flowpowered.network.pipeline.MessageProcessorDecoderTest.java
License:MIT License
@Test public void test() throws Exception { // Preprocessor basically is split into two parts // Part 1 is just a direct copy // Part 2 negates all bytes before copying final AtomicReference<MessageProcessor> processor = new AtomicReference<>(); MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) { @Override/* w w w . j a v a 2 s. c o m*/ protected MessageProcessor getProcessor() { return processor.get(); } }; // Set up a fake ChannelHandlerContext FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup(); AtomicReference<ByteBuf> ref = new AtomicReference<>(); fake.setReference(ref); LinkedList<byte[]> outputList = new LinkedList<>(); Random r = new Random(); // Get some random bytes for data byte[] input = new byte[LENGTH]; r.nextBytes(input); boolean breakOccured = false; int position = 0; for (int i = 0; i < input.length;) { // Simulate real data read int burstSize = r.nextInt(512); // With a 1/10 chance of having an extra-large burst if (r.nextInt(10) == 0) { burstSize *= 10; } // Final burst needs to be clamped if (i + burstSize > input.length) { burstSize = input.length - i; } // And we can't negate in the middle of a burst if (i + burstSize > BREAK && !breakOccured) { burstSize = BREAK - i; } // Write info to a new ByteBuf final ByteBuf buf = Unpooled.buffer(burstSize); buf.writeBytes(input, i, burstSize); i += burstSize; // Fake a read processorDecoder.channelRead(fake, buf); final ByteBuf returned = ref.get(); while (returned != null) { int packetSize = r.nextInt(128) + 1; if (r.nextInt(10) == 0) { packetSize *= 20; } if (packetSize > returned.readableBytes()) { packetSize = returned.readableBytes(); } if (position + packetSize > BREAK && !breakOccured) { packetSize = BREAK - position; } if (position + packetSize > LENGTH) { packetSize = LENGTH - position; } if (packetSize == 0) { break; } byte[] array = new byte[packetSize]; returned.readBytes(array); position += packetSize; if (position == BREAK) { processor.set(new NegatingProcessor(512)); breakOccured = true; } outputList.add(array); } } // Get the output data and combine into one array byte[] output = new byte[LENGTH]; int i = 0; for (byte[] array : outputList) { for (int j = 0; j < array.length; j++) { output[i++] = array[j]; } } for (i = 0; i < input.length; i++) { byte expected = i < BREAK ? input[i] : (byte) ~input[i]; if (output[i] != expected) { for (int j = Math.max(0, i - 10); j <= i + 10; j++) { System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j]) + " " + Integer.toBinaryString(output[j])); } } if (i < BREAK) { assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got " + output[i] + ". Break is: " + BREAK, output[i] == input[i]); } else { assertTrue( "Input/Output mismatch at position " + i + ", after the processor change. Expected " + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK, output[i] == (byte) ~input[i]); } } }
From source file:com.flowpowered.network.pipeline.MessageProcessorEncoder.java
License:MIT License
@Override protected void encode(ChannelHandlerContext ctx, final ByteBuf buf, List<Object> out) throws Exception { final MessageProcessor processor = getProcessor(); if (processor == null) { out.add(buf.readBytes(buf.readableBytes())); return;// w ww.jav a 2 s . c om } ByteBuf toAdd = ctx.alloc().buffer(); toAdd = processor.processOutbound(ctx, buf, toAdd); out.add(toAdd); }
From source file:com.flowpowered.network.util.ByteBufUtils.java
License:MIT License
/** * Reads an UTF8 string from a byte buffer. * * @param buf The byte buffer to read from * @return The read string//from w w w .jav a2 s . co m * @throws java.io.IOException If the reading fails */ public static String readUTF8(ByteBuf buf) throws IOException { // Read the string's length final int len = readVarInt(buf); final byte[] bytes = new byte[len]; buf.readBytes(bytes); return new String(bytes, StandardCharsets.UTF_8); }
From source file:com.flowpowered.networking.pipeline.MessageDecoder.java
License:MIT License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { Protocol protocol = messageHandler.getSession().getProtocol(); Codec<?> codec = null;/*from www .j a va2 s . c om*/ try { codec = protocol.readHeader(buf); } catch (UnknownPacketException e) { // We want to catch this and read the length if possible int length = e.getLength(); if (length != -1 && length != 0) { buf.readBytes(length); } throw e; } if (codec == null) { throw new UnsupportedOperationException("Protocol#readHeader cannot return null!"); } Message decoded = codec.decode(buf); ctx.fireChannelRead(decoded); }
From source file:com.flowpowered.networking.pipeline.MessageProcessorDecoderTest.java
License:MIT License
@Test public void test() throws Exception { // Preprocessor basically is split into two parts // Part 1 is just a direct copy // Part 2 negates all bytes before copying final AtomicReference<MessageProcessor> processor = new AtomicReference<>(); MessageProcessorDecoder processorDecoder = new MessageProcessorDecoder(null) { @Override//from ww w . java 2 s . c om protected MessageProcessor getProcessor() { return processor.get(); } }; // Set up a fake ChannelHandlerContext FakeChannelHandlerContext fake = ChannelHandlerContextFaker.setup(); AtomicReference<ByteBuf> ref = new AtomicReference<>(); fake.setReference(ref); LinkedList<byte[]> outputList = new LinkedList<byte[]>(); Random r = new Random(); // Get some random bytes for data byte[] input = new byte[LENGTH]; r.nextBytes(input); boolean breakOccured = false; int position = 0; for (int i = 0; i < input.length;) { // Simulate real data read int burstSize = r.nextInt(512); // With a 1/10 chance of having an extra-large burst if (r.nextInt(10) == 0) { burstSize *= 10; } // Final burst needs to be clamped if (i + burstSize > input.length) { burstSize = input.length - i; } // And we can't negate in the middle of a burst if (i + burstSize > BREAK && !breakOccured) { burstSize = BREAK - i; } // Write info to a new ByteBuf final ByteBuf buf = Unpooled.buffer(burstSize); buf.retain(); buf.writeBytes(input, i, burstSize); i += burstSize; // Fake a read processorDecoder.channelRead(fake, buf); final ByteBuf returned = ref.get(); while (returned != null && true) { int packetSize = r.nextInt(128) + 1; if (r.nextInt(10) == 0) { packetSize *= 20; } if (packetSize > returned.readableBytes()) { packetSize = returned.readableBytes(); } if (position + packetSize > BREAK && !breakOccured) { packetSize = BREAK - position; } if (position + packetSize > LENGTH) { packetSize = LENGTH - position; } if (packetSize == 0) { break; } byte[] array = new byte[packetSize]; returned.readBytes(array); position += packetSize; if (position == BREAK) { processor.set(new NegatingProcessor(512)); breakOccured = true; } outputList.add(array); } } // Get the output data and combine into one array byte[] output = new byte[LENGTH]; int i = 0; for (byte[] array : outputList) { for (int j = 0; j < array.length; j++) { output[i++] = array[j]; } } for (i = 0; i < input.length; i++) { byte expected = i < BREAK ? input[i] : (byte) ~input[i]; if (output[i] != expected) { for (int j = Math.max(0, i - 10); j <= i + 10; j++) { System.out.println(j + ") " + Integer.toBinaryString(j < BREAK ? input[j] : (byte) ~input[j]) + " " + Integer.toBinaryString(output[j])); } } if (i < BREAK) { assertTrue("Input/Output mismatch at position " + i + ". Expected " + input[i] + " but got " + output[i] + ". Break is: " + BREAK, output[i] == input[i]); } else { assertTrue( "Input/Output mismatch at position " + i + ", after the processor change. Expected " + (byte) ~input[i] + " but got " + output[i] + ". Break is: " + BREAK, output[i] == (byte) ~input[i]); } } }
From source file:com.foilen.smalltools.net.commander.channel.CommanderDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { logger.debug("Trying to decode a message. Readable bytes {}", in.readableBytes()); // classNameSize:int int len = in.readInt(); // className:String String className = in.readBytes(len).toString(CharsetTools.UTF_8); // jsonContentSize:int len = in.readInt();/*from w w w . ja v a2 s . co m*/ // jsonContent:String String jsonContent = in.readBytes(len).toString(CharsetTools.UTF_8); // Add the JSON runnable to the list logger.debug("Decoding class {} with json {}", className, jsonContent); out.add(JsonTools.readFromString(jsonContent, Class.forName(className))); logger.debug("Completely got a {}", className); }