Example usage for io.netty.handler.codec MessageToByteEncoder MessageToByteEncoder

List of usage examples for io.netty.handler.codec MessageToByteEncoder MessageToByteEncoder

Introduction

In this page you can find the example usage for io.netty.handler.codec MessageToByteEncoder MessageToByteEncoder.

Prototype

protected MessageToByteEncoder() 

Source Link

Document

see #MessageToByteEncoder(boolean) with true as boolean parameter.

Usage

From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean inject() {
    synchronized (networkManager) {
        if (closed)
            return false;
        if (originalChannel instanceof Factory)
            return false;
        if (!originalChannel.isActive())
            return false;

        // Main thread? We should synchronize with the channel thread, otherwise we might see a
        // pipeline with only some of the handlers removed
        if (Bukkit.isPrimaryThread()) {
            // Just like in the close() method, we'll avoid blocking the main thread
            executeInChannelThread(new Runnable() {
                @Override/*from w  ww  .ja v a  2 s . c om*/
                public void run() {
                    inject();
                }
            });
            return false; // We don't know
        }

        // Don't inject the same channel twice
        if (findChannelHandler(originalChannel, NettyChannelInjector.class) != null) {
            return false;
        }

        // Get the vanilla decoder, so we don't have to replicate the work
        vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder");
        vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder");

        if (vanillaDecoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla decoder in " + originalChannel.pipeline());
        if (vanillaEncoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla encoder in " + originalChannel.pipeline());
        patchEncoder(vanillaEncoder);

        if (DECODE_BUFFER == null)
            DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode",
                    ChannelHandlerContext.class, ByteBuf.class, List.class);
        if (ENCODE_BUFFER == null)
            ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode",
                    ChannelHandlerContext.class, Object.class, ByteBuf.class);

        // Intercept sent packets
        MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
                if (packet instanceof WirePacket) {
                    // Special case for wire format
                    NettyChannelInjector.this.encodeWirePacket((WirePacket) packet, new NettyByteBuf(output));
                } else {
                    NettyChannelInjector.this.encode(ctx, packet, output);
                }
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise)
                    throws Exception {
                super.write(ctx, packet, promise);
                NettyChannelInjector.this.finalWrite(ctx, packet, promise);
            }
        };

        // Intercept recieved packets
        ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                // Execute context first
                ctx.fireChannelRead(msg);
                NettyChannelInjector.this.finishRead(ctx, msg);
            }
        };

        // Insert our handlers - note that we effectively replace the vanilla encoder/decoder
        originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this);
        originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler);
        originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder);

        // Intercept all write methods
        channelField.setValue(new NettyChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) {
            // Compatibility with Spigot 1.8
            private final NettyPipelineProxy pipelineProxy = new NettyPipelineProxy(originalChannel.pipeline(),
                    this) {
                @Override
                public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
                    // Correct the position of the decoder
                    if ("decoder".equals(baseName)) {
                        if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) {
                            super.addBefore("protocol_lib_decoder", name, handler);
                            return this;
                        }
                    }

                    return super.addBefore(baseName, name, handler);
                }
            };

            @Override
            public ChannelPipeline pipeline() {
                return pipelineProxy;
            }

            @Override
            protected <T> Callable<T> onMessageScheduled(final Callable<T> callable,
                    FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(callable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        T result = null;

                        // This field must only be updated in the pipeline thread
                        currentEvent = event;
                        result = callable.call();
                        currentEvent = null;
                        return result;
                    }
                };
            }

            @Override
            protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(runnable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Runnable() {
                    @Override
                    public void run() {
                        currentEvent = event;
                        runnable.run();
                        currentEvent = null;
                    }
                };
            }

            protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) {
                // Let the filters handle this packet
                Object original = accessor.get(instance);

                // See if we've been instructed not to process packets
                if (!scheduleProcessPackets.get()) {
                    NetworkMarker marker = getMarker(original);

                    if (marker != null) {
                        PacketEvent result = new PacketEvent(NettyChannelInjector.class);
                        result.setNetworkMarker(marker);
                        return result;
                    } else {
                        return BYPASSED_PACKET;
                    }
                }
                PacketEvent event = processSending(original);

                if (event != null && !event.isCancelled()) {
                    Object changed = event.getPacket().getHandle();

                    // Change packet to be scheduled
                    if (original != changed)
                        accessor.set(instance, changed);
                }
                ;
                return event != null ? event : BYPASSED_PACKET;
            }
        });

        injected = true;
        return true;
    }
}

From source file:com.comphenix.protocol.injector.netty.ChannelInjector.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean inject() {
    synchronized (networkManager) {
        if (closed)
            return false;
        if (originalChannel instanceof Factory)
            return false;
        if (!originalChannel.isActive())
            return false;

        // Main thread? We should synchronize with the channel thread, otherwise we might see a
        // pipeline with only some of the handlers removed
        if (Bukkit.isPrimaryThread()) {
            // Just like in the close() method, we'll avoid blocking the main thread
            executeInChannelThread(new Runnable() {
                @Override// www. j  av a 2 s  .  c  o  m
                public void run() {
                    inject();
                }
            });
            return false; // We don't know
        }

        // Don't inject the same channel twice
        if (findChannelHandler(originalChannel, ChannelInjector.class) != null) {
            return false;
        }

        // Get the vanilla decoder, so we don't have to replicate the work
        vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder");
        vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder");

        if (vanillaDecoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla decoder in " + originalChannel.pipeline());
        if (vanillaEncoder == null)
            throw new IllegalArgumentException(
                    "Unable to find vanilla encoder in " + originalChannel.pipeline());
        patchEncoder(vanillaEncoder);

        if (DECODE_BUFFER == null)
            DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode",
                    ChannelHandlerContext.class, ByteBuf.class, List.class);
        if (ENCODE_BUFFER == null)
            ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode",
                    ChannelHandlerContext.class, Object.class, ByteBuf.class);

        // Intercept sent packets
        MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() {
            @Override
            protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
                if (packet instanceof WirePacket) {
                    // Special case for wire format
                    ChannelInjector.this.encodeWirePacket((WirePacket) packet, output);
                } else {
                    ChannelInjector.this.encode(ctx, packet, output);
                }
            }

            @Override
            public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise)
                    throws Exception {
                super.write(ctx, packet, promise);
                ChannelInjector.this.finalWrite(ctx, packet, promise);
            }
        };

        // Intercept recieved packets
        ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                // Execute context first
                ctx.fireChannelRead(msg);
                ChannelInjector.this.finishRead(ctx, msg);
            }
        };

        // Insert our handlers - note that we effectively replace the vanilla encoder/decoder
        originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this);
        originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler);
        originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder);

        // Intercept all write methods
        channelField.setValue(new ChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) {
            // Compatibility with Spigot 1.8
            private final PipelineProxy pipelineProxy = new PipelineProxy(originalChannel.pipeline(), this) {
                @Override
                public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) {
                    // Correct the position of the decoder
                    if ("decoder".equals(baseName)) {
                        if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) {
                            super.addBefore("protocol_lib_decoder", name, handler);
                            return this;
                        }
                    }

                    return super.addBefore(baseName, name, handler);
                }
            };

            @Override
            public ChannelPipeline pipeline() {
                return pipelineProxy;
            }

            @Override
            protected <T> Callable<T> onMessageScheduled(final Callable<T> callable,
                    FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(callable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        T result = null;

                        // This field must only be updated in the pipeline thread
                        currentEvent = event;
                        result = callable.call();
                        currentEvent = null;
                        return result;
                    }
                };
            }

            @Override
            protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) {
                final PacketEvent event = handleScheduled(runnable, packetAccessor);

                // Handle cancelled events
                if (event != null && event.isCancelled())
                    return null;

                return new Runnable() {
                    @Override
                    public void run() {
                        currentEvent = event;
                        runnable.run();
                        currentEvent = null;
                    }
                };
            }

            protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) {
                // Let the filters handle this packet
                Object original = accessor.get(instance);

                // See if we've been instructed not to process packets
                if (!scheduleProcessPackets.get()) {
                    NetworkMarker marker = getMarker(original);

                    if (marker != null) {
                        PacketEvent result = new PacketEvent(ChannelInjector.class);
                        result.setNetworkMarker(marker);
                        return result;
                    } else {
                        return BYPASSED_PACKET;
                    }
                }
                PacketEvent event = processSending(original);

                if (event != null && !event.isCancelled()) {
                    Object changed = event.getPacket().getHandle();

                    // Change packet to be scheduled
                    if (original != changed)
                        accessor.set(instance, changed);
                }
                ;
                return event != null ? event : BYPASSED_PACKET;
            }
        });

        injected = true;
        return true;
    }
}

From source file:com.github.liyp.netty.App.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {/*from  ww  w. ja v  a 2  s .c  om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override//w w w  .  java2s  . c  om
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}

From source file:org.enderstone.server.packet.NetworkManager.java

License:Open Source License

public void setupEncryption(final SecretKey key) throws IOException {
    final Cipher decrypter = generateKey(2, key);
    final Cipher encrypter = generateKey(1, key);
    ctx.pipeline().addBefore("packet_rw_converter", "decrypt", new MessageToMessageDecoder<ByteBuf>() {

        NetworkEncrypter chipper = new NetworkEncrypter(decrypter);

        @Override/*  ww  w. ja v a 2  s. c  o m*/
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                throws ShortBufferException {
            System.out.println("Decrypting " + in.readableBytes());
            this.chipper.decrypt(ctx, in);
        }

    });
    ctx.pipeline().addBefore("packet_rw_converter", "encrypt", new MessageToByteEncoder<ByteBuf>() {

        NetworkEncrypter chipper = new NetworkEncrypter(encrypter);

        @Override
        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
            System.out.println("Encrypting " + msg.readableBytes());
            this.chipper.encrypt(msg, out);
        }

    });
}