Example usage for io.netty.handler.codec.serialization ObjectDecoder ObjectDecoder

List of usage examples for io.netty.handler.codec.serialization ObjectDecoder ObjectDecoder

Introduction

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

Prototype

public ObjectDecoder(ClassResolver classResolver) 

Source Link

Document

Creates a new decoder whose maximum object size is 1048576 bytes.

Usage

From source file:afred.javademo.proxy.rpc.ObjectEchoClient.java

License:Apache License

public void start(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {// ww  w . j  a v a 2 s  . c o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
        });

        channel = b.connect(host, port).sync().channel();
    } finally {

    }
}

From source file:afred.javademo.proxy.rpc.ObjectEchoServer.java

License:Apache License

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

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from ww w  .  j a  v  a  2 s.co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(8080).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:ChatClient.ChatClientInitializer.java

@Override
protected void initChannel(SocketChannel c) throws Exception {
    ChannelPipeline pipeline = c.pipeline();

    pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())));
    pipeline.addLast("encoder", new ObjectEncoder());

    pipeline.addLast("handler", new ChatClientHandler());
}

From source file:ChatServer.ChatServerInitializer.java

@Override
protected void initChannel(SocketChannel c) throws Exception {
    ChannelPipeline pipeline = c.pipeline();

    pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader())));
    pipeline.addLast("encoder", new ObjectEncoder());
    pipeline.addLast("handler", new ChatServerHandler());
}

From source file:com.avanza.astrix.netty.client.NettyRemotingClient.java

License:Apache License

public void connect(String host, int port) {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override//from   w  w  w.  j  av a 2 s.  c o m
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                    nettyRemotingClientHandler);
        }
    });

    // Start the connection attempt.
    ChannelFuture channel = b.connect(host, port);
    try {
        if (channel.await(1, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    destroy();
    throw new IllegalArgumentException(
            String.format("Failed to connect to remoting server: %s:%d", host, port));
}

From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w  ww  . java  2 s  . c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new NettyRemotingServerHandler(serviceActivator));
                }
            });

    // Bind and start to accept incoming connections. Binds to all interfaces
    // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port
    ChannelFuture channel = b.bind(port);
    try {
        if (channel.await(2, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort();
                log.info("NettyRemotingServer started listening on port={}", port);
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port);
}

From source file:com.baidu.rigel.biplatform.ma.file.client.service.impl.FileServerClient.java

License:Open Source License

/**
 * ?/*from   w  ww.  j  a  v  a2 s.  c o  m*/
 * 
 * @param server
 *            ??
 * @param port
 *            ??
 * @param request
 *            
 * @return 
 */
public Response doRequest(String server, int port, final Request request) {
    EventLoopGroup work = new NioEventLoopGroup(1);
    String message = null;
    try {
        final Response rs = new Response(ResponseStatus.FAIL, "failed", null);
        ChannelHandlerAdapter requestHandler = new ChannelHandlerAdapter() {

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                logger.info("successfully connect to file server");
                ctx.write(request);
                ctx.flush();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                logger.info("successfuly recieve message from file server {}", msg);
                Response tmpRs = (Response) msg;
                rs.setDatas(tmpRs.getDatas());
                rs.setMessage(tmpRs.getMessage());
                rs.setStatus(tmpRs.getStatus());
                ctx.close();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                ctx.flush();
            }

            /**
             * {@inheritDoc}
             */
            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                logger.error(cause.getMessage());
                rs.setMessage(cause.getMessage());
                rs.setStatus(ResponseStatus.FAIL);
                ctx.close();
            }
        };
        Bootstrap strap = new Bootstrap();
        strap.group(work).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel chl) throws Exception {
                        // ??
                        chl.pipeline().addLast(new ObjectDecoder(
                                ClassResolvers.cacheDisabled(requestHandler.getClass().getClassLoader())));
                        chl.pipeline().addLast(new ObjectEncoder());
                        chl.pipeline().addLast(requestHandler);
                    }

                });
        long begin = System.currentTimeMillis();
        logger.debug("Begin invoke do file operation request ... ...");
        ChannelFuture future = strap.connect(server, port);
        future.channel().closeFuture().sync();
        logger.debug(
                "Success execute request option cost time: " + (System.currentTimeMillis() - begin) + "ms");
        return rs;
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
        message = e.getMessage();
    } finally {
        work.shutdownGracefully();
    }
    Response rs = new Response(ResponseStatus.FAIL, message, null);
    return rs;
}

From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java

License:Open Source License

private static void startServer(String location, int port) {
    fileLocation = new FileLocation(location);
    service = new LocalFileOperationServiceImpl(fileLocation);
    EventLoopGroup bossGroup = new NioEventLoopGroup(10);
    EventLoopGroup workGroup = new NioEventLoopGroup(50);
    try {//from w w  w  .  ja  va  2s . co  m
        ServerBootstrap strap = new ServerBootstrap();
        strap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        // ??
                        channel.pipeline().addLast(new ObjectDecoder(ClassResolvers
                                .weakCachingConcurrentResolver(FileServer.class.getClassLoader())));
                        channel.pipeline().addLast(new ObjectEncoder());
                        //                        channel.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                        channel.pipeline().addLast(new FileServer());
                    }
                });
        ChannelFuture future = strap.bind(port).sync();
        LOGGER.info("start file server successfully");
        LOGGER.info("port : " + port);
        LOGGER.info("location : " + location);
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        LOGGER.error("can not start file server with [port : {}] and fileLocation {{}}", port, location);
        printUsage();
        System.exit(-1);
    } finally {
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchClient.java

License:Open Source License

public IndexAndSearchClient() {
    // channelMaps = new ConcurrentHashMap<NodeAddress, Channel>();
    actionHandlerMaps = new ConcurrentHashMap<String, ChannelHandler>();
    b = new Bootstrap();
    group = new NioEventLoopGroup();
    b.group(group);//from   w w w .  j a  va 2 s . com
    b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("encode", new ObjectEncoder());
            pipeline.addLast("decode", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
            //                pipeline.addLast("frameencoder",new LengthFieldPrepender(4,false));
            //                pipeline.addLast("framedecoder",new LengthFieldBasedFrameDecoder(1024*1024*1024, 0, 4,0,4));
        }
    });

    logger.info("IndexAndSearchClient init finished");
}

From source file:com.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchServer.java

License:Open Source License

/**
 * startServer// w ww .  j  a v  a 2  s .c om
 * 
 * @throws Exception
 */
protected void startServer() throws Exception {
    LOGGER.info("Index and Search server ready to start...");
    long curr = System.currentTimeMillis();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 1000000);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            /*
             * (non-Javadoc)
             * 
             * @see
             * io.netty.channel.ChannelInitializer#initChannel(io.netty.
             * channel.Channel)
             */
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encode", new ObjectEncoder());
                pipeline.addLast("decode",
                        new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                pipeline.addLast(IndexServerHandler.getChannelHandler());
                pipeline.addLast(SearchServerHandler.getChannelHandler());
                pipeline.addLast(FileServerHandler.getChannelHandler());
            }

        });

        // ChannelFuture f = b.bind(IP, PORT).sync();
        // f.channel().closeFuture().sync();

        int currPort = NetworkUtils.getAvailablePort(this.node.getPort());

        ChannelFuture f = b.bind(IP, currPort).sync();

        if (currPort != this.node.getPort()) {
            this.node.setPort(currPort);
        }

        serverChannelFuture = f;
        LOGGER.info("Index and Search server started at Port:" + this.node.getPort());
        LOGGER.info("Index and Search server started in " + (System.currentTimeMillis() - curr) + "ms");
        this.isRunning = true;

        serverChannelFuture.channel().closeFuture().sync().channel();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}