List of usage examples for io.netty.buffer ByteBuf capacity
public abstract int capacity();
From source file:com.flysoloing.learning.network.netty.udt.echo.rendezvous.MsgEchoPeerHandler.java
License:Apache License
public MsgEchoPeerHandler(final int messageSize) { super(false); final ByteBuf byteBuf = Unpooled.buffer(messageSize); for (int i = 0; i < byteBuf.capacity(); i++) { byteBuf.writeByte((byte) i); }/*from w ww . ja v a 2 s . c om*/ message = new UdtMessage(byteBuf); }
From source file:com.ghrum.common.protocol.MessageLookupService.java
License:Apache License
/** * Encodes a {@link Message} into a stream * * @param message the message to encode to the buffer * @return a wrapped buffer that contains the header and the body of the message * @throws java.io.IOException//from w w w .j a v a 2 s . c o m */ @SuppressWarnings("unchecked") protected <T extends Message> ByteBuf encode(T message) throws IOException { final MessageCodec<Message> codec = (MessageCodec<Message>) getCodec(message.getClass()); if (codec == null) { throw new IOException("Unknown operation class: " + message.getClass()); } final ByteBuf body = codec.encode(message); final ByteBuf header = Unpooled.buffer(3).writeByte(codec.getOpcode()).writeShort(body.capacity()); return Unpooled.wrappedBuffer(header, body); }
From source file:com.github.gregwhitaker.requestreply.Client.java
License:Apache License
public void start() throws Exception { Publisher<ClientTcpDuplexConnection> publisher = ClientTcpDuplexConnection.create(remoteAddress, new NioEventLoopGroup(1)); ClientTcpDuplexConnection duplexConnection = RxReactiveStreams.toObservable(publisher).toBlocking().last(); ReactiveSocket reactiveSocket = DefaultReactiveSocket.fromClientConnection(duplexConnection, ConnectionSetupPayload.create("UTF-8", "UTF-8"), t -> t.printStackTrace()); reactiveSocket.startAndWait();/*from w ww . j a v a 2s. c o m*/ // Create an observable that emits messages at a specific interval. Publisher<Payload> requestStream = RxReactiveStreams.toPublisher( Observable.interval(1_000, TimeUnit.MILLISECONDS).onBackpressureDrop().map(i -> new Payload() { @Override public ByteBuffer getData() { return ByteBuffer.wrap(("YO " + i).getBytes()); } @Override public ByteBuffer getMetadata() { return Frame.NULL_BYTEBUFFER; } })); final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE); requestStream.subscribe(new Subscriber<Payload>() { @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onNext(Payload payload) { ByteBuf buffer = Unpooled.buffer(payload.getData().capacity()); buffer.writeBytes(payload.getData()); byte[] bytes = new byte[buffer.capacity()]; buffer.readBytes(bytes); System.out.println("Client Sent: " + new String(bytes)); reactiveSocket.requestResponse(payload).subscribe(new Subscriber<Payload>() { @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onNext(Payload payload) { ByteBuf buffer = Unpooled.buffer(payload.getData().capacity()); buffer.writeBytes(payload.getData()); byte[] bytes = new byte[buffer.capacity()]; buffer.readBytes(bytes); System.out.println("Client Received: " + new String(bytes)); latch.countDown(); } @Override public void onError(Throwable t) { latch.countDown(); } @Override public void onComplete() { latch.countDown(); } }); } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); latch.await(); System.exit(0); }
From source file:com.github.spapageo.jannel.channel.ChannelBufferUtilsTest.java
License:Open Source License
@Test public void testWriteStringToOctetStringIsEncodedCorrectly() throws Exception { ByteBuf encodedString = Unpooled.copiedBuffer(STRING_TO_ENCODE.getBytes(StandardCharsets.UTF_8)); ByteBuf outputBuffer = Unpooled.buffer(4 + encodedString.capacity()); ChannelBufferUtils.writeStringToOctetString(STRING_TO_ENCODE, outputBuffer, StandardCharsets.UTF_8); assertEquals("Written length prefix in not the length of the encoded string byte array", encodedString.capacity(), outputBuffer.readInt()); assertEquals("Written bytes are not the same with those of the input string", encodedString, outputBuffer); outputBuffer.release();/*w w w . j a v a2s . c o m*/ encodedString.release(); }
From source file:com.github.spapageo.jannel.channel.ChannelBufferUtilsTest.java
License:Open Source License
@Test public void testWriteUUIDToOctetStringIsEncodedCorrectly() throws Exception { UUID input = UUID.randomUUID(); String uuidString = input.toString(); ByteBuf encodedUUID = Unpooled.copiedBuffer(uuidString.getBytes(StandardCharsets.UTF_8)); ByteBuf outputBuffer = Unpooled.buffer(4 + encodedUUID.capacity()); ChannelBufferUtils.writeUUIDToOctetString(input, outputBuffer, StandardCharsets.UTF_8); assertEquals("Written length prefix in not the length of the encoded string byte array", encodedUUID.capacity(), outputBuffer.readInt()); assertEquals("Written bytes are not the same with those of the input string", encodedUUID, outputBuffer); outputBuffer.release();/*from ww w .j ava 2s. co m*/ encodedUUID.release(); }
From source file:com.hop.hhxx.example.udt.echo.message.MsgEchoClientHandler.java
License:Apache License
public MsgEchoClientHandler() { super(false); final ByteBuf byteBuf = Unpooled.buffer(io.netty.example.udt.echo.message.MsgEchoClient.SIZE); for (int i = 0; i < byteBuf.capacity(); i++) { byteBuf.writeByte((byte) i); }/*w w w .ja va2 s .c om*/ message = new UdtMessage(byteBuf); }
From source file:com.ibm.crail.datanode.netty.CrailNettyUtils.java
License:Apache License
public static void showByteBufContent(ByteBuf buf, int offset, int bytes) { /* this dump the content of first bytes from the payload */ if (buf != null) { int ori_rindex = buf.readerIndex(); LOG.info("DUMP: TID:" + Thread.currentThread().getId() + " NettyByteBuf : " + buf); int min = (buf.capacity() - offset); if (min > bytes) min = bytes;//w w w. j av a 2s .c o m String str = "DUMP: TID:" + Thread.currentThread().getId() + " DUMP (" + offset + " ,+" + min + ") : "; //for loop update it to the end limit min += offset; for (int i = offset; i < min; i++) { //str += Character.toHexString(); str += Byte.toString(buf.getByte(i)) + " : "; if (i % 32 == 0) str += "\n"; } LOG.info(str); buf.readerIndex(ori_rindex); } else { LOG.info("DUMP : payload content is NULL"); } }
From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java
License:Apache License
private ByteBuf serializeProto(Message message) throws IOException { if (GrpcSerializationFormats.isProto(serializationFormat)) { final ByteBuf buf = alloc.buffer(message.getSerializedSize()); boolean success = false; try {/*from w ww.j av a2 s . c o m*/ message.writeTo(CodedOutputStream.newInstance(buf.nioBuffer(0, buf.writableBytes()))); buf.writerIndex(buf.capacity()); success = true; } finally { if (!success) { buf.release(); } } return buf; } if (GrpcSerializationFormats.isJson(serializationFormat)) { final ByteBuf buf = alloc.buffer(); boolean success = false; try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) { jsonMarshaller.writeValue(message, os); success = true; } finally { if (!success) { buf.release(); } } return buf; } throw new IllegalStateException("Unknown serialization format: " + serializationFormat); }
From source file:com.mobius.software.android.iotbroker.mqtt.net.MQDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { ByteBuf nextHeader = null; do {// w w w. j av a 2s .c om if (buf.readableBytes() > 1) nextHeader = MQParser.next(buf); if (nextHeader != null) { buf.readBytes(nextHeader, nextHeader.capacity()); try { MQMessage header = MQParser.decode(nextHeader); out.add(header); } catch (Exception e) { buf.resetReaderIndex(); ctx.channel().pipeline().remove(this); throw e; } finally { nextHeader.release(); } } } while (buf.readableBytes() > 1 && nextHeader != null); }
From source file:com.mobius.software.mqtt.performance.controller.net.Decoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) { ByteBuf nextHeader = null; do {//from www. j a va2s.c o m if (buf.readableBytes() > 1) { try { nextHeader = MQParser.next(buf); } catch (MalformedMessageException | IndexOutOfBoundsException ex) { buf.resetReaderIndex(); if (nextHeader != null) nextHeader = null; } } if (nextHeader != null) { buf.readBytes(nextHeader, nextHeader.capacity()); try { MQMessage header = MQParser.decode(nextHeader); out.add(header); } catch (Exception e) { buf.resetReaderIndex(); ctx.channel().pipeline().remove(this); throw e; } finally { nextHeader.release(); } } } while (buf.readableBytes() > 1 && nextHeader != null); }