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:org.kwh.tcp.server.ServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf in = (ByteBuf) msg;//from  w  ww . j  a  va2  s .com
    try {
        logger.info("New packet received");
        String receivedContent = in.toString(io.netty.util.CharsetUtil.US_ASCII);
        // send back message to the datalogger to notify it the bytes were
        // correctly received
        byte[] response = "@888\n".getBytes();
        final ByteBuf buffer = ctx.alloc().buffer(response.length);
        buffer.writeBytes(response);
        ctx.writeAndFlush(buffer);
        Consumer cons = new Consumer(receivedContent);
        es.submit(cons);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        in.release();
    }
}

From source file:org.lanternpowered.pingy.PingyFramingHandler.java

License:MIT License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> output) throws Exception {
    while (readableVarInt(buf)) {
        buf.markReaderIndex();/*from  ww  w  .  ja v  a 2s.c o  m*/

        final int length = readVarInt(buf);
        if (buf.readableBytes() < length) {
            buf.resetReaderIndex();
            break;
        }

        final ByteBuf msg = ctx.alloc().buffer(length);
        buf.readBytes(msg, length);

        output.add(msg);
    }
}

From source file:org.lanternpowered.pingy.PingyHandler.java

License:MIT License

private static ChannelFuture sendMessage(ChannelHandlerContext ctx, int messageId,
        Consumer<ByteBuf> bufConsumer) {
    final ByteBuf buf = ctx.alloc().buffer();
    writeVarInt(buf, messageId);//from   w w  w.j  a va2s  . co m
    bufConsumer.accept(buf);
    return ctx.writeAndFlush(buf);
}

From source file:org.lanternpowered.pingy.PingyLegacyHandler.java

License:MIT License

/**
 * Sends a disconnect message to a legacy client and closes the connection.
 *
 * @param ctx The channel handler context
 * @param message The message/*from   w w  w  .ja va2s .c o m*/
 */
private static void sendLegacyDisconnectMessage(ChannelHandlerContext ctx, String message) {
    byte[] data = message.getBytes(StandardCharsets.UTF_16BE);

    ByteBuf output = ctx.alloc().buffer();
    output.writeByte(0xff);
    output.writeShort(data.length >> 1);
    output.writeBytes(data);

    ctx.pipeline().firstContext().writeAndFlush(output).addListener(ChannelFutureListener.CLOSE);
}

From source file:org.lanternpowered.server.network.pipeline.LegacyProtocolHandler.java

License:MIT License

/**
 * Sends a disconnect message to a legacy client and closes the connection.
 *
 * @param ctx The channel handler context
 * @param message The message/*from ww w . j a v  a  2  s  .  c  o m*/
 */
private static void sendDisconnectMessage(ChannelHandlerContext ctx, String message) {
    final byte[] data = message.getBytes(StandardCharsets.UTF_16BE);

    final ByteBuf output = ctx.alloc().buffer();
    output.writeByte(0xff);
    output.writeShort(data.length >> 1);
    output.writeBytes(data);

    ctx.channel().pipeline().firstContext().writeAndFlush(output).addListener(ChannelFutureListener.CLOSE);
}

From source file:org.lanternpowered.server.network.pipeline.MessageCodecHandler.java

License:MIT License

@Override
protected void encode(ChannelHandlerContext ctx, Message message, List<Object> output) throws Exception {
    final Protocol protocol = this.codecContext.getSession().getProtocol();
    final MessageRegistration<Message> registration = (MessageRegistration<Message>) protocol.outbound()
            .findByMessageType(message.getClass()).orElse(null);

    if (registration == null) {
        throw new EncoderException("Message type (" + message.getClass().getName() + ") is not registered!");
    }/*from w  w  w  . j a  va2  s  . c  o m*/
    CodecRegistration codecRegistration = registration.getCodecRegistration().orElse(null);
    if (codecRegistration == null) {
        throw new EncoderException(
                "Message type (" + message.getClass().getName() + ") is not registered to allow encoding!");
    }

    /*
    if (message instanceof MessagePlayOutWorldTime ||
        message instanceof MessageInOutKeepAlive) {
    } else {
    System.out.println(message.getClass().getName());
    }
    */

    final ByteBuf opcode = ctx.alloc().buffer();

    // Write the opcode of the message
    writeVarInt(opcode, codecRegistration.getOpcode());

    final Codec codec = codecRegistration.getCodec();
    final ByteBuffer content;
    try {
        content = codec.encode(this.codecContext, message);
    } finally {
        ReferenceCountUtil.release(message);
    }

    // Add the buffer to the output
    output.add(Unpooled.wrappedBuffer(opcode, ((LanternByteBuffer) content).getDelegate()));
}

From source file:org.lanternpowered.server.network.pipeline.MessageCompressionHandler.java

License:MIT License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    ByteBuf prefixBuf = ctx.alloc().buffer(5);
    ByteBuf contentsBuf;/*from  ww  w.  j a v a2s  . co m*/

    if (msg.readableBytes() >= this.compressionThreshold) {
        // Message should be compressed
        int index = msg.readerIndex();
        int length = msg.readableBytes();

        byte[] sourceData = new byte[length];
        msg.readBytes(sourceData);
        this.deflater.setInput(sourceData);
        this.deflater.finish();

        byte[] compressedData = new byte[length];
        int compressedLength = this.deflater.deflate(compressedData);
        this.deflater.reset();

        if (compressedLength == 0) {
            // Compression failed in some weird way
            throw new EncoderException("Failed to compress message of size " + length);
        } else if (compressedLength >= length) {
            // Compression increased the size. threshold is probably too low
            // Send as an uncompressed packet
            writeVarInt(prefixBuf, 0);
            msg.readerIndex(index);
            msg.retain();
            contentsBuf = msg;
        } else {
            // All is well
            writeVarInt(prefixBuf, length);
            contentsBuf = Unpooled.wrappedBuffer(compressedData, 0, compressedLength);
        }
    } else {
        // Message should be sent through
        writeVarInt(prefixBuf, 0);
        msg.retain();
        contentsBuf = msg;
    }

    out.add(Unpooled.wrappedBuffer(prefixBuf, contentsBuf));
}

From source file:org.lanternpowered.server.network.pipeline.MessageCompressionHandler.java

License:MIT License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    int index = msg.readerIndex();
    int uncompressedSize = readVarInt(msg);
    if (uncompressedSize == 0) {
        // Message is uncompressed
        int length = msg.readableBytes();
        if (length >= this.compressionThreshold) {
            // Invalid
            throw new DecoderException("Received uncompressed message of size " + length
                    + " greater than threshold " + this.compressionThreshold);
        }//from w  w w  .  java 2  s  .  com

        ByteBuf buf = ctx.alloc().buffer(length);
        msg.readBytes(buf, length);
        out.add(buf);
    } else {
        // Message is compressed
        byte[] sourceData = new byte[msg.readableBytes()];
        msg.readBytes(sourceData);
        this.inflater.setInput(sourceData);

        byte[] destData = new byte[uncompressedSize];
        int resultLength = this.inflater.inflate(destData);
        this.inflater.reset();

        if (resultLength == 0) {
            // Might be a leftover from before compression was enabled (no compression header)
            // UncompressedSize is likely to be < threshold
            msg.readerIndex(index);
            msg.retain();
            out.add(msg);
        } else if (resultLength != uncompressedSize) {
            throw new DecoderException("Received compressed message claiming to be of size " + uncompressedSize
                    + " but actually " + resultLength);
        } else {
            out.add(Unpooled.wrappedBuffer(destData));
        }
    }
}

From source file:org.lanternpowered.server.network.pipeline.MessageFramingHandler.java

License:MIT License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> output) throws Exception {
    int length;/*www .ja  v  a  2 s  .co m*/
    while ((length = readableMessage(buf)) != -1) {
        final ByteBuf msg = ctx.alloc().buffer(length);
        buf.readBytes(msg, length);
        output.add(msg);
    }
}

From source file:org.lanternpowered.server.network.query.QueryHandler.java

License:MIT License

private void handleHandshake(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    int challengeToken = queryServer.generateChallengeToken(packet.sender());
    ByteBuf out = ctx.alloc().buffer();
    out.writeByte(ACTION_HANDSHAKE);//from  w w w  .j a v a2 s. c  o  m
    out.writeInt(sessionId);
    writeString(out, String.valueOf(challengeToken));
    ctx.write(new DatagramPacket(out, packet.sender()));
}