Example usage for io.netty.channel.socket DatagramPacket replace

List of usage examples for io.netty.channel.socket DatagramPacket replace

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramPacket replace.

Prototype

@Override
    public DatagramPacket replace(ByteBuf content) 

Source Link

Usage

From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.trace("SourcePacketHandler.channelRead() : START");

    try {/*from  w w  w. j a v  a2  s  . com*/
        //Make sure we are only receiving an instance of DatagramPacket
        if (!(msg instanceof DatagramPacket)) {
            return;
        }

        final DatagramPacket packet = (DatagramPacket) msg;
        final ByteBuf data = ((DatagramPacket) msg).content();

        //Verify size
        if (data.readableBytes() <= 5) {
            log.debug(
                    "Not a valid datagram for processing. Size getTotalRequests needs to be at least more than or equal to 5 bytes. Discarding. (Readable Bytes: {})",
                    data.readableBytes());
            return;
        }

        //Try to read protocol header, determine if its a single packet or a split-packet
        int protocolHeader = data.readIntLE();

        //If the packet arrived is single type, we can already forward it to the next handler
        if (protocolHeader == 0xFFFFFFFF) {
            //Pass the message to the succeeding handlers
            ctx.fireChannelRead(packet.retain());
            return;
        }
        //If the packet is a split type...we need to process each succeeding read until we have a complete packet
        else if (protocolHeader == 0xFFFFFFFE) {
            final ByteBuf reassembledPacket = processSplitPackets(data, ctx.channel().alloc(), packet.sender());
            //Check if we already have a reassembled packet
            if (reassembledPacket != null) {
                ctx.fireChannelRead(packet.replace(reassembledPacket));
                return;
            }
        }
        //Packet is not being handled by any of our processors, discard
        else {
            log.debug("Not a valid protocol header. Discarding. (Header Received: Dec = {}, Hex = {})",
                    protocolHeader, Integer.toHexString(protocolHeader));
            return;
        }
    } catch (Exception e) {
        log.error(String.format("Error while processing packet for %s", ((DatagramPacket) msg).sender()), e);
        throw e;
    } finally {
        //Release the message
        ReferenceCountUtil.release(msg);
    }
    log.trace("SourcePacketHandler.channelRead() : END");
}