Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:io.vertx.core.http.impl.Http2ConnectionBase.java

License:Open Source License

@Override
public synchronized int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
        boolean endOfStream) {
    int[] consumed = { padding };
    VertxHttp2Stream req = streams.get(streamId);
    if (req != null) {
        data = safeBuffer(data, ctx.alloc());
        Buffer buff = Buffer.buffer(data);
        context.executeFromIO(() -> {
            int len = buff.length();
            if (req.onDataRead(buff)) {
                consumed[0] += len;/* www.  j  a  v a 2  s .co  m*/
            }
        });
        if (endOfStream) {
            context.executeFromIO(req::onEnd);
        }
    }
    return consumed[0];
}

From source file:io.vertx.core.net.impl.VertxHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
    Object message = safeObject(msg, chctx.alloc());
    C connection = getConnection();/* w  ww  . j  a va2  s .  c  o m*/

    ContextImpl context;
    if (connection != null) {
        context = getContext(connection);
        context.executeFromIO(connection::startRead);
    } else {
        context = null;
    }
    channelRead(connection, context, chctx, message);
}

From source file:jazmin.server.msg.codec.json.JSONEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ResponseMessage msg, ByteBuf out) throws Exception {
    //send raw data
    if (msg.rawData != null) {
        out.writeBytes(msg.rawData);//from  ww w.  ja v a2 s. com
        return;
    }
    //
    ResponseProto bean = new ResponseProto();
    bean.d = (System.currentTimeMillis());
    bean.ri = (msg.requestId);
    bean.rsp = (msg.responseMessages);
    bean.si = (msg.serviceId);
    bean.sc = (msg.statusCode);
    bean.sm = (msg.statusMessage);
    String json = JSON.toJSONString(bean) + "\n";
    if (logger.isDebugEnabled()) {
        logger.debug("\nencode message--------------------------------------\n" + DumpUtil.formatJSON(json));
    }
    ByteBuf result = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(json), charset);
    out.writeBytes(result);
    networkTrafficStat.outBound(json.getBytes().length);
}

From source file:lunarion.node.requester.test.TestLunarClientHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    System.out.println("client @channelActive..");
    ctx.writeAndFlush(firstMessage);//from  w  ww  . j  a  v  a  2s.com

    for (int i = 0; i < 10; i++) {
        byte[] req = ("messenge " + i).getBytes();
        ByteBuf nextMessage = ctx.alloc().buffer(req.length);

        nextMessage = Unpooled.buffer(req.length);
        nextMessage.writeBytes(req);
        ctx.writeAndFlush(nextMessage); // (3)
        //Thread.sleep(2000);
    }
}

From source file:me.ferrybig.p2pnetwork.codec.PacketPreProcessor.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, Packet msg) throws Exception {
    try {//from   w  ww  . j ava2s. c o m
        Address from;
        Function<Packet, ChannelFuture> reply;
        if (msg instanceof RelayPacket) {
            RelayPacket relayPacket = (RelayPacket) msg;
            int packetId = relayPacket.getData().readInt();
            from = relayPacket.getFrom();
            msg = PacketMap.readPacket(packetId, relayPacket.getData());
            relayPacket.release(); // This is a safe release
            reply = p -> {
                ByteBuf wrapped = ctx.alloc().buffer();
                try {
                    wrapped.writeInt(PacketMap.getPacketId(p));
                    p.write(wrapped);
                    return ctx.writeAndFlush(
                            new RelayPacket(wrapped.retain(), relayPacket.getAddress(), from, 255));
                } finally {
                    p.release();
                    wrapped.release();
                }
            };
        } else {
            from = connection;
            reply = ctx::writeAndFlush;
        }
        ctx.fireChannelRead(new ProcessedPacket(from, ctx.channel(), (Packet) msg.retain(), reply));
    } finally {
        msg.release();
    }
}

From source file:me.ferrybig.p2pnetwork.codec.PacketRoutingHandler.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, RelayPacket msg) throws Exception {
    if (msg.getAddress().equals(ourself)) {
        ctx.fireChannelRead(msg.retain());
        return;/*from   w  w w  .  j av  a 2s  .  c  o m*/
    }
    if (msg.getTtl() == 0) {
        DestinationUnreachablePacket result = new DestinationUnreachablePacket(
                DestinationUnreachablePacket.Reason.TTL_EXPIRED, msg.getAddress());
        try {

            ByteBuf buf = ctx.alloc().buffer();
            buf.writeInt(PacketMap.getPacketId(result));
            result.write(buf);
            ctx.writeAndFlush(new RelayPacket(buf, ourself, msg.getFrom(), 127));
        } finally {
            result.release();
        }
        return;
    }
    msg.decrementTTL();
    if (!router.apply(msg)) {
        DestinationUnreachablePacket result = new DestinationUnreachablePacket(
                DestinationUnreachablePacket.Reason.DESTINATION_HOST_UNREACHABLE, msg.getAddress());
        try {
            ByteBuf buf = ctx.alloc().buffer();
            result.write(buf);
            ctx.write(buf);
            ctx.writeAndFlush(new RelayPacket(buf));
        } finally {
            result.release();
        }
    }
}

From source file:me.netty.http.handler.HelloWorldHttp2Handler.java

License:Apache License

/**
 * If receive a frame with end-of-stream set, send a pre-canned response.
 *//* w  ww .  j a va2  s. c o  m*/
public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception {
    if (headers.isEndStream()) {
        ByteBuf content = ctx.alloc().buffer();
        content.writeBytes(RESPONSE_BYTES.duplicate());
        ByteBufUtil.writeAscii(content, " - via HTTP/2");
        sendResponse(ctx, content);
    }

    logger.debug("get header stream id is : " + headers.streamId());
}

From source file:net.minecrell.quartz.mixin.network.MixinLegacyPingHandler.java

License:MIT License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    this.buf = ctx.alloc().buffer();
}

From source file:net.NettyEngine4.ServerDecoder.java

License:Apache License

/**
 * decode message will be added the MessageList<Object> out  queue!
 * @param ctx//from   w w  w  .  j  av  a 2  s. c  o 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.petercashel.nettyCore.client.ClientConnectionHander.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    buf = ctx.alloc().buffer(Packet.packetBufSize + Packet.packetHeaderSize); // (1)
}