List of usage examples for io.netty.buffer ByteBuf readBytes
public abstract int readBytes(FileChannel out, long position, int length) throws IOException;
From source file:TestTCPServer.java
License:Open Source License
public static void main(String... args) throws Throwable { IOService service = new IOService(); TCPAcceptor acceptor = new TCPAcceptor(service); acceptor.setOption(ChannelOption.SO_BACKLOG, 3); acceptor.setChildOption(ChannelOption.TCP_NODELAY, true); acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true); acceptor.bind(4321);//from w w w. j a v a2 s. c o m TCPSocket con = acceptor.accept(); ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000); byte[] bytea = new byte[buffer.capacity()]; long bytes; System.out.println("Connected " + con.remoteEndpoint()); bytes = con.receive(buffer); while (bytes != -1 && buffer.getByte(0) != 4) { buffer.readBytes(bytea, 0, (int) bytes); System.out.print(new String(bytea, 0, (int) bytes)); buffer.readerIndex(0).writerIndex(0); con.send(buffer, (int) bytes); buffer.readerIndex(0).writerIndex(0); bytes = con.receive(buffer); } System.out.println("Connection closed"); con.close(); acceptor.close(); service.cancel(); }
From source file:alluxio.client.block.stream.PacketInStream.java
License:Apache License
@Override public int positionedRead(long pos, byte[] b, int off, int len) throws IOException { if (len == 0) { return 0; }//from w w w .j a v a 2s . com if (pos < 0 || pos >= mLength) { return -1; } int lenCopy = len; try (PacketReader reader = mPacketReaderFactory.create(pos, len)) { // We try to read len bytes instead of returning after reading one packet because // it is not free to create/close a PacketReader. while (len > 0) { ByteBuf buf = null; try { buf = reader.readPacket(); if (buf == null) { break; } Preconditions.checkState(buf.readableBytes() <= len); int toRead = buf.readableBytes(); buf.readBytes(b, off, toRead); len -= toRead; off += toRead; } finally { if (buf != null) { buf.release(); } } } } if (lenCopy == len) { return -1; } return lenCopy - len; }
From source file:appeng.util.item.AEFluidStack.java
License:Open Source License
public static IAEFluidStack loadFluidStackFromPacket(final ByteBuf data) throws IOException { final byte mask = data.readByte(); // byte PriorityType = (byte) (mask & 0x03); final byte stackType = (byte) ((mask & 0x0C) >> 2); final byte countReqType = (byte) ((mask & 0x30) >> 4); final boolean isCraftable = (mask & 0x40) > 0; final boolean hasTagCompound = (mask & 0x80) > 0; // don't send this... final NBTTagCompound d = new NBTTagCompound(); final byte len2 = data.readByte(); final byte[] name = new byte[len2]; data.readBytes(name, 0, len2); d.setString("FluidName", new String(name, "UTF-8")); d.setByte("Count", (byte) 0); if (hasTagCompound) { final int len = data.readInt(); final byte[] bd = new byte[len]; data.readBytes(bd);//w ww . j a va2 s . c o m final DataInputStream di = new DataInputStream(new ByteArrayInputStream(bd)); d.setTag("tag", CompressedStreamTools.read(di)); } // long priority = getPacketValue( PriorityType, data ); final long stackSize = getPacketValue(stackType, data); final long countRequestable = getPacketValue(countReqType, data); final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(d); if (fluidStack == null) { return null; } final AEFluidStack fluid = AEFluidStack.create(fluidStack); // fluid.priority = (int) priority; fluid.setStackSize(stackSize); fluid.setCountRequestable(countRequestable); fluid.setCraftable(isCraftable); return fluid; }
From source file:buildcraft.builders.TileBlueprintLibrary.java
License:Minecraft Mod Public
@Override public void receiveCommand(String command, Side side, Object sender, ByteBuf stream) { if (side.isClient()) { if ("requestSelectedBlueprint".equals(command)) { if (isOutputConsistent()) { if (selected > -1 && selected < currentPage.size()) { // Work around 32k max limit on client->server final BlueprintBase bpt = BuildCraftBuilders.clientDB.load(currentPage.get(selected)); final byte[] bptData = bpt.getData(); final int chunks = (bptData.length + CHUNK_SIZE - 1) / CHUNK_SIZE; BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadServerBegin", new CommandWriter() { public void write(ByteBuf data) { bpt.id.writeData(data); data.writeShort(chunks); }/*from w w w . j a v a 2s .c o m*/ })); for (int i = 0; i < chunks; i++) { final int chunk = i; final int start = CHUNK_SIZE * chunk; final int length = Math.min(CHUNK_SIZE, bptData.length - start); BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadServerChunk", new CommandWriter() { public void write(ByteBuf data) { data.writeShort(chunk); data.writeShort(length); data.writeBytes(bptData, start, length); } })); } BuildCraftCore.instance.sendToServer(new PacketCommand(this, "uploadServerEnd", null)); } else { BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadNothingToServer", null)); } } } else if ("downloadBlueprintToClient".equals(command)) { BlueprintId id = new BlueprintId(); id.readData(stream); byte[] data = Utils.readByteArray(stream); try { NBTTagCompound nbt = CompressedStreamTools.func_152457_a(data, NBTSizeTracker.field_152451_a); BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt); bpt.setData(data); bpt.id = id; BuildCraftBuilders.clientDB.add(bpt); setCurrentPage(BuildCraftBuilders.clientDB.getPage(pageId)); } catch (IOException e) { e.printStackTrace(); } } } else if (side.isServer()) { if ("uploadNothingToServer".equals(command)) { setInventorySlotContents(3, getStackInSlot(2)); setInventorySlotContents(2, null); downloadingPlayer = null; } else if ("uploadServerBegin".equals(command)) { blueprintDownloadId = new BlueprintId(); blueprintDownloadId.readData(stream); blueprintDownload = new byte[CHUNK_SIZE * stream.readUnsignedShort()]; } else if ("uploadServerChunk".equals(command)) { int start = stream.readUnsignedShort() * CHUNK_SIZE; int length = stream.readUnsignedShort(); if (blueprintDownload != null) { stream.readBytes(blueprintDownload, start, length); } else { stream.skipBytes(length); } } else if ("uploadServerEnd".equals(command)) { try { NBTTagCompound nbt = CompressedStreamTools.func_152457_a(blueprintDownload, NBTSizeTracker.field_152451_a); BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt); bpt.setData(blueprintDownload); bpt.id = blueprintDownloadId; BuildCraftBuilders.serverDB.add(bpt); setInventorySlotContents(3, bpt.getStack()); setInventorySlotContents(2, null); } catch (IOException e) { e.printStackTrace(); } blueprintDownloadId = null; blueprintDownload = null; downloadingPlayer = null; } } }
From source file:buildcraft.robotics.TileZonePlan.java
License:Minecraft Mod Public
@Override public void readData(ByteBuf stream) { progress = stream.readShort();// w w w. ja va 2s . co m mapName = NetworkUtils.readUTF(stream); stream.readBytes(previewColors, 0, 80); previewColorsPushed = false; }
From source file:com.aerofs.baseline.http.EntityInputStream.java
License:Apache License
@Override public synchronized int read(@Nonnull byte[] b, int off, int len) throws IOException { // basic argument checks // pulled straight from InputStream if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; }/*from w ww . j ava2 s. c o m*/ // if the sender already closed // the stream then we're going to // abort, *even if* the sender // has already sent the bytes we // care about throwIfClosed(); // we may have to send a 100 CONTINUE // if the client specifically requests // it. to prevent the server from buffering // bytes we only send it the moment the // app thread starts reading from the // stream. this can be changed easily sendContinueIfRequested(); int initialOffset = off; int bufferRemaining = len; while (true) { // get bytes from the network getNetworkBytes(); // how many bytes can we read? int remaining = inputCompleted ? (int) Math.min(readable, bufferRemaining) : bufferRemaining; if (remaining == 0) { break; } Preconditions.checkState(!buffers.isEmpty(), "readable bytes, but no buffers"); // read as much as required // from the top buffer ByteBuf head = buffers.get(0); int chunkReadable = Math.min(head.readableBytes(), remaining); head.readBytes(b, off, chunkReadable); // bookkeeping readable -= chunkReadable; off += chunkReadable; bufferRemaining -= chunkReadable; // remove the top buffer if it's exhausted if (head.readableBytes() == 0) { buffers.remove(0); head.release(); } } return off == initialOffset ? -1 : off - initialOffset; }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
/** public static byte[] readBytesWithNull(ByteBuf in) { final byte[] b = this.data;/*from ww w. jav a2 s. co m*/ if (position >= length) { return EMPTY_BYTES; } int offset = -1; for (int i = position; i < length; i++) { if (b[i] == 0) { offset = i; break; } } switch (offset) { case -1: byte[] ab1 = new byte[length - position]; System.arraycopy(b, position, ab1, 0, ab1.length); position = length; return ab1; case 0: position++; return EMPTY_BYTES; default: byte[] ab2 = new byte[offset - position]; System.arraycopy(b, position, ab2, 0, ab2.length); position = offset + 1; return ab2; } } */ public static byte[] readBytesWithLength(ByteBuf in) { int length = (int) in.readByte(); if (length == NULL_LENGTH) { return null; } if (length <= 0) { return EMPTY_BYTES; } byte[] ab = new byte[length]; in.readBytes(ab, 0, length); return ab; }
From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java
License:Open Source License
public static byte[] readBytes(ByteBuf in, int length) { if (length == NULL_LENGTH) { return null; }// w ww. j ava 2 s .c o m if (length <= 0) { return EMPTY_BYTES; } byte[] ab = new byte[length]; in.readBytes(ab, 0, length); return ab; }
From source file:com.baidu.jprotobuf.pbrpc.transport.handler.RpcDataPackageDecoder.java
License:Apache License
protected Object decode(ChannelHandlerContext ctx, ByteBuf buf) throws Exception { // Make sure if the length field was received. if (buf.readableBytes() < RpcHeadMeta.SIZE) { // The length field was not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. return null; }/*from w w w .j a v a 2s.c o m*/ // The length field is in the buffer. // Mark the current buffer position before reading the length field // because the whole frame might not be in the buffer yet. // We will reset the buffer position to the marked position if // there's not enough bytes in the buffer. buf.markReaderIndex(); // Read the RPC head long rpcMessageDecoderStart = System.nanoTime(); ByteBuffer buffer = buf.nioBuffer(buf.readerIndex(), RpcHeadMeta.SIZE); buffer.order(ByteOrder.LITTLE_ENDIAN); byte[] bytes = new byte[RpcHeadMeta.SIZE]; buffer.get(bytes); RpcHeadMeta headMeta = new RpcHeadMeta(); headMeta.read(bytes); // get total message size int messageSize = headMeta.getMessageSize() + RpcHeadMeta.SIZE; // Make sure if there's enough bytes in the buffer. if (buf.readableBytes() < messageSize) { // The whole bytes were not received yet - return null. // This method will be invoked again when more packets are // received and appended to the buffer. // Reset to the marked position to read the length field again // next time. buf.resetReaderIndex(); return null; } // check magic code String magicCode = headMeta.getMagicCodeAsString(); if (!ProtocolConstant.MAGIC_CODE.equals(magicCode)) { throw new Exception("Error magic code:" + magicCode); } // There's enough bytes in the buffer. Read it. byte[] totalBytes = new byte[messageSize]; buf.readBytes(totalBytes, 0, messageSize); RpcDataPackage rpcDataPackage = new RpcDataPackage(); rpcDataPackage.setTimeStamp(System.currentTimeMillis()); rpcDataPackage.read(totalBytes); // check if a chunk package if (rpcDataPackage.isChunkPackage()) { Long chunkStreamId = rpcDataPackage.getChunkStreamId(); RpcDataPackage chunkDataPackage = tempTrunkPackages.get(chunkStreamId); if (chunkDataPackage == null) { chunkDataPackage = rpcDataPackage; tempTrunkPackages.put(chunkStreamId, rpcDataPackage); } else { chunkDataPackage.mergeData(rpcDataPackage.getData()); } if (rpcDataPackage.isFinalPackage()) { chunkDataPackage.chunkInfo(chunkStreamId, -1); tempTrunkPackages.remove(chunkStreamId); return chunkDataPackage; } return null; } long rpcMessageDecoderEnd = System.nanoTime(); LOG.log(Level.FINE, "[profiling] nshead decode cost : " + (rpcMessageDecoderEnd - rpcMessageDecoderStart) / 1000); return rpcDataPackage; }
From source file:com.basho.riak.client.core.netty.RiakHttpMessageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { message = new RiakHttpMessage((HttpResponse) msg); }/*from w w w . j ava 2s . c o m*/ if (msg instanceof HttpContent) { /** TODO: commented for compilation * chunks.add(((HttpContent)msg).data().retain()); * totalContentLength += ((HttpContent)msg).data().readableBytes(); */ if (msg instanceof LastHttpContent) { byte[] bytes = new byte[totalContentLength]; int index = 0; for (ByteBuf buffer : chunks) { int readable = buffer.readableBytes(); buffer.readBytes(bytes, index, readable); index += readable; buffer.release(); } int responseCode = message.getResponse().getStatus().code(); message.setContent(bytes); /** TODO: commented for compilation if ( responseCode < 200 || (responseCode >= 400 && responseCode != 404 && responseCode != 412 ) ) { listener.onException(chc.channel(), new RiakResponseException(responseCode, new String(bytes))); } else { message.setContent(bytes); listener.onSuccess(chc.channel(), message); } chc.channel().pipeline().remove(this); */ } } }