Java 类io.netty.handler.codec.serialization.ObjectEncoder 实例源码

项目:star-map    文件:StarServerProtocol.java   
@Override
public void openServer(URL url) throws Exception{
    EventLoopGroup eventLoop = new NioEventLoopGroup();
    EventLoopGroup workLoop = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(eventLoop, workLoop);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>(){

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))) // in 1
                    .addLast("handler", new ServerHandler()) // in 2
                    .addLast("encoder", new ObjectEncoder()); // out 3

        }
    });
    serverChannel = serverBootstrap.bind(url.getPort()).sync().sync().channel();
    logger.info("start server at:" + url.getPort());
}
项目:star-map    文件:StarClientProtocol.java   
@Override
    public void open() {
        EventLoopGroup eventLoop = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3 * 1000);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
//                        .addLast("logging",new LoggingHandler(LogLevel.INFO))
                        .addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(getClass().getClassLoader()))) // in 1
                        .addLast("handler", new ClientReadHandler()) // in 2
                        .addLast("encoder", new ObjectEncoder())// out 3
                        .addLast("idleStateHandler", new IdleStateHandler(0, 1, 0))
                        .addLast(new ClientIdleHandler());

            }
        });
    }
项目:mini-dubbo    文件:NettyServer.java   
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
项目:netty-tutorials    文件:PojoClient.java   
public void send() throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder());
                    p.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                    p.addLast(new PojoClientHandler());
                }
            });

            ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
项目:netty    文件:NettyClientBootstrap.java   
private void start() throws InterruptedException {
    EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
    Bootstrap bootstrap=new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
    bootstrap.group(eventLoopGroup);
    bootstrap.remoteAddress(host,port);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new IdleStateHandler(20,10,0));
            socketChannel.pipeline().addLast(new ObjectEncoder());
            socketChannel.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            socketChannel.pipeline().addLast(new NettyClientHandler());
        }
    });
    ChannelFuture future =bootstrap.connect(host,port).sync();
    if (future.isSuccess()) {
        socketChannel = (SocketChannel)future.channel();
        System.out.println("connect server  成功---------");
    }
}
项目:netty    文件:NettyServerBootstrap.java   
private void bind() throws InterruptedException {
    EventLoopGroup boss=new NioEventLoopGroup();
    EventLoopGroup worker=new NioEventLoopGroup();
    ServerBootstrap bootstrap=new ServerBootstrap();
    bootstrap.group(boss,worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline p = socketChannel.pipeline();
            p.addLast(new ObjectEncoder());
            p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            p.addLast(new NettyServerHandler());
        }
    });
    ChannelFuture f= bootstrap.bind(port).sync();
    if(f.isSuccess()){
        System.out.println("server start---------------");
    }
}
项目:SecureSmartHome    文件:ClientHandshakeHandler.java   
/**
 * Called once the TCP connection is established.
 * Configures the per-connection pipeline that is responsible for handling incoming and outgoing data.
 * After an incoming packet is decrypted, decoded and verified,
 * it will be sent to its target {@link de.unipassau.isl.evs.ssh.core.handler.MessageHandler}
 * by the {@link IncomingDispatcher}.
 */
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    Log.v(TAG, "channelRegistered " + ctx);
    ctx.attr(ATTR_HANDSHAKE_FINISHED).set(false);

    // Add (de-)serialization Handlers before this Handler
    ctx.pipeline().addBefore(ctx.name(), ObjectEncoder.class.getSimpleName(), new ObjectEncoder());
    ctx.pipeline().addBefore(ctx.name(), ObjectDecoder.class.getSimpleName(), new ObjectDecoder(
            ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
    ctx.pipeline().addBefore(ctx.name(), LoggingHandler.class.getSimpleName(), new LoggingHandler(LogLevel.TRACE));

    // Timeout Handler
    ctx.pipeline().addBefore(ctx.name(), IdleStateHandler.class.getSimpleName(),
            new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    ctx.pipeline().addBefore(ctx.name(), TimeoutHandler.class.getSimpleName(), new TimeoutHandler());

    // Add exception handler
    ctx.pipeline().addAfter(ctx.name(), PipelinePlug.class.getSimpleName(), new PipelinePlug());

    super.channelRegistered(ctx);
    Log.v(TAG, "Pipeline after register: " + ctx.pipeline());
}
项目:NPush    文件:ServerInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    /*
     * 使用ObjectDecoder和ObjectEncoder
     * 因为双向都有写数据和读数据,所以这里需要两个都设置
     * 如果只读,那么只需要ObjectDecoder即可
     */
    pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
    pipeline.addLast("encoder", new ObjectEncoder());

    /*
     * 这里只监听读操作
     * 可以根据需求,监听写操作和总得操作
     */
    pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, Constants.ALL_IDLE_TIME, TimeUnit.SECONDS));

    pipeline.addLast("handler", new ServerHandler());
}
项目:javase-study    文件:ObjectEchoServer.java   
private void run(int port) throws InterruptedException, IOException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO))
                                .addLast(new ObjectEncoder())
                                .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                .addLast(new ObjectEchoServerHandler());
                    }
                });
        bootstrap.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
项目:javase-study    文件:ObjectEchoClient.java   
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO))
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                    .addLast(new ObjectEchoClientHandler());
                        }
                    });

            bootstrap.connect(host, port).sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
项目:javase-study    文件:ObjectEchoServer.java   
private void run(int port) throws InterruptedException, IOException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO))
//                                    .addLast(new LengthFieldBasedFrameDecoder(200, 0, 4, 0, 4))
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                    .addLast(new ObjectEchoServerHandler());
                        }
                    });
            bootstrap.bind(port).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
项目:javase-study    文件:ObjectEchoClient.java   
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG))
//                                    .addLast(new LengthFieldPrepender(4))
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                    .addLast(new ObjectEchoClientHandler());
                        }
                    });

            bootstrap.connect(host, port).sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
项目:netty4study    文件:ObjectEchoServer.java   
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoServerHandler());
            }
         });

        // Bind and start to accept incoming connections.
        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:netty4study    文件:ObjectEchoClient.java   
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler(firstMessageSize));
            }
         });

        // Start the connection attempt.
        b.connect(host, port).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
项目:jumbune    文件:Remoter.java   
/**
 * Fire and forget command.
 *  Example usage: CommandWritable commandWritable = new CommandWritable();
    commandWritable.setCommandString("Sending Command");
    remoter.fireAndForgetCommand(commandWritable);
 * @param command the command
 */
public void fireAndForgetCommand(CommandWritable commandWritable) {
    ChannelFuture channelFuture;
    CyclicBarrier barrier = new CyclicBarrier(2);
    List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();

    handlers.add(new ObjectEncoder());
    StringResponseHandler stringResponseHandler = new StringResponseHandler();
    handlers.add(new StringDecoder());
    handlers.add(stringResponseHandler);
    channelFuture = acquireChannelFuture("CMD", handlers);
    // sending barrier as channel attachment for dynamic integration of
    // barrier
    writeToChannel(channelFuture.channel(), new String[] { "C", "M", "D" }, commandWritable, barrier);

    confirmBarrierAndGo(barrier);
    addCloseListener(channelFuture);
    channelFuture.channel().close();
}
项目:jumbune    文件:Remoter.java   
/**
 * Fire and forget command asynchronous
 *  Example usage: CommandWritable commandWritable = new CommandWritable();
    commandWritable.setCommandString("Sending Command");
    remoter.fireAndForgetCommandAsync(commandWritable);
 * @param command the command
 */
//TODO: test fireAsyncAndForgetCommand method, create async method for fire and get object response 
public void fireAsyncAndForgetCommand(CommandWritable commandWritable) {
    ChannelFuture channelFuture;
    CyclicBarrier barrier = new CyclicBarrier(2);
    List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();
    handlers.add(new ObjectEncoder());
    StringResponseHandler stringResponseHandler = new StringResponseHandler();
    handlers.add(new StringDecoder());
    handlers.add(stringResponseHandler);
    channelFuture = acquireChannelFuture("CMA", handlers);

    writeToChannel(channelFuture.channel(), new String[] { "C", "M", "A" }, commandWritable, barrier);
    confirmBarrierAndGo(barrier);
    addCloseListener(channelFuture);
    channelFuture.channel().close();
}
项目:jumbune    文件:Remoter.java   
/**
 * Fire typed command and get object response.
 * Example Usage:
 *  CommandWritable commandWritable = new CommandWritable();
    commandWritable.setCommandForMaster(true);
    commandWritable.setUsername("JumbuneUser");
    remoter.fireCommandAndGetObjectResponse(commandWritable);

 * @param command the command
 * @return the object
 */
public Object fireCommandAndGetObjectResponse(CommandWritable commandWritable) {
    ChannelFuture channelFuture;
    // Eventually fallen back on battle tested CyclicBarrier, await(),
    // sync() on ChannelFuture didn't worked
    CyclicBarrier barrier = new CyclicBarrier(2);

    List<ChannelHandler> handlers = new LinkedList<ChannelHandler>();
    ObjectResponseHandler objectResponseHandler = new ObjectResponseHandler(barrier);
    handlers.add(new ObjectEncoder());
    handlers.add(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
    handlers.add(objectResponseHandler);

    channelFuture = acquireChannelFuture("CMO", handlers);
    writeToChannel(channelFuture.channel(), new String[] { "C", "M", "O" }, commandWritable, objectResponseHandler);

    confirmBarrierAndGo(barrier);
    channelFuture.channel().close();
    return objectResponseHandler.getResponseObject();
}
项目:darks-grid    文件:CodecFactory.java   
public static ChannelHandler createEncoder()
{
    CodecConfig codecConfig = GridRuntime.config().getNetworkConfig().getCodecConfig();
    String type = DEFAULT_CODEC;
    Class<? extends GridCodec> codecClass = null;
    if (codecConfig.getType() != null)
    {
        type = codecConfig.getType().toLowerCase();
        codecClass = codecConfig.getCodecClass();
    }
    if (NETTY_CODEC.equals(type))
    {
        return new ObjectEncoder();
    }
    if (codecMap.containsKey(type) && codecClass == null)
    {
        codecClass = codecMap.get(type);
    }
    if (codecClass == null)
        throw new GridException("Cannot find codec " + type);
    GridCodec codec = ReflectUtils.newInstance(codecClass);
    codec.initialize(codecConfig.getParameters());
    return new GridObjectEncoder(codec);
}
项目:netty-netty-5.0.0.Alpha1    文件:ObjectEchoServer.java   
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoServerHandler());
            }
         });

        // Bind and start to accept incoming connections.
        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:ObjectEchoClient.java   
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler(firstMessageSize));
            }
         });

        // Start the connection attempt.
        b.connect(host, port).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
项目:archistar-core    文件:OzymandiasClient.java   
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {

    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);

    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });

    return b.connect("127.0.0.1", port).sync().channel();
}
项目:push-server    文件:NettyClientInitializer.java   
@Override
protected void initChannel(Channel channel) throws Exception {
    //IdleStateHandler检测心跳.
    ChannelPipeline p = channel.pipeline();
    p.addLast(new IdleStateHandler(20, 10, 0));
    p.addLast(new ObjectEncoder());
    p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
    p.addLast(new NettyClientHandler());
}
项目:push-server    文件:NettyServerInitializer.java   
@Override
protected void initChannel(Channel channel) throws Exception {
    ChannelPipeline p = channel.pipeline();
    p.addLast(new ObjectEncoder());
    p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
    p.addLast(new NettyServerHandler());
}
项目:java_learn    文件:SubReqClient.java   
public void connect(int port, String host) throws InterruptedException {

    EventLoopGroup group = new NioEventLoopGroup();
    try{
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //解码
                ch.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers
                        .weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                //编码
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new SubReqClientHandler());
            }

        });

        //发送异步链接操作
        ChannelFuture f = b.connect(host, port).sync();
        //等待客户端链路关闭
        f.channel().closeFuture().sync();
    }finally{
        group.shutdownGracefully();
    }

}
项目:java_learn    文件:SubReqServer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    //解码
    ch.pipeline().addLast(new ObjectDecoder(1024*1024, ClassResolvers
            .weakCachingConcurrentResolver(this.getClass().getClassLoader())));
    //编码
    ch.pipeline().addLast(new ObjectEncoder());
    ch.pipeline().addLast(new SubReqServerHandler());
}
项目:slim-map-reduce    文件:SortClientInitializer.java   
/**
 * Initialized the channel pipeline.
 */
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("client_decoder", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));  
    pipeline.addLast("client_encoder", new ObjectEncoder());
    pipeline.addLast("client_handler", new SortClientHandler());
}
项目:slim-map-reduce    文件:SortServerInitializer.java   
/**
 * Initialized the channel pipeline.
 */
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("server_decoder", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));  
    pipeline.addLast("server_encoder", new ObjectEncoder());    
    pipeline.addLast("server_handler", new SortServerHandler());
}
项目:netty-tutorials    文件:PojoServer.java   
public void run() throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder());
                    p.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                    p.addLast(new PojoServerHandler());
                }
            });

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

            logger.info("server bind port:{}", port);

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
项目:NetChess    文件:NettyServer.java   
public void run() throws InterruptedException {
    log.debug("run at host={}, port={}", host, port);
    bossGroup = new NioEventLoopGroup(BOSS_GROUP_THREADS);
    workerGroup = new NioEventLoopGroup(WORKER_GROUP_THREADS);

    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(final SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                //new LoggingHandler(LogLevel.INFO),
                                new ObjectEncoder(),
                                new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new NetChessServerHandler()
                        );
                    }
                })
                .option(ChannelOption.SO_BACKLOG, CHANNEL_SO_BACKLOG)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        channelFuture = b.bind(host, port).sync();
        log.info("Server started at host={}, port={}", host, port);
    } catch (final InterruptedException ex) {
        log.error("run; host={}, port={}", host, port, ex);
        // В случае исключения - освобождаем ресурсы и перебрасываем исключение в функцию выше
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        throw ex;
    }
}
项目:NetChess    文件:NettyClient.java   
public void run() throws InterruptedException, ConnectException {
    log.debug("run; host={}, port={}", host, port);
    workerGroup = new NioEventLoopGroup(WORKER_GROUP_THREADS);

    try {
        final Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(final SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEncoder(),
                        new NetChessClientHandler()
                );
            }
        });

        channelFuture = b.connect(host, port).sync();
        log.info("Client connected to server (host={}, port={})", host, port);
    } catch (final InterruptedException ex) {
        log.error("run; host={}, port={}", host, port, ex);
        // В случае исключения - освобождаем ресурсы и перебрасываем исключение выше
        workerGroup.shutdownGracefully();
        throw ex;
    }
}
项目:MercuryTrade    文件:ClientChannelInitializer.java   
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    socketChannel.pipeline().addLast(new ObjectEncoder());
    ClassLoader classLoader = this.getClass().getClassLoader();
    ClassResolver classResolver = ClassResolvers.weakCachingResolver(classLoader);
    socketChannel.pipeline().addLast(new ObjectDecoder(classResolver));
    socketChannel.pipeline().addLast(new ClientHandler());
}
项目:JavaAyo    文件:ObjectEchoServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        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();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoServerHandler());
            }
         });

        // Bind and start to accept incoming connections.
        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:JavaAyo    文件:ObjectEchoClient.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        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();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
         });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
项目:SecureSmartHome    文件:ServerHandshakeHandler.java   
/**
 * Configures the per-connection pipeline that is responsible for handling incoming and outgoing data.
 * After an incoming packet is decrypted, decoded and verified,
 * it will be sent to its target {@link MessageHandler}
 * by the {@link IncomingDispatcher}.
 */
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    Log.v(TAG, "channelRegistered " + ctx);
    if (container == null) {
        //Do not accept new connections after the Server has been shut down
        Log.v(TAG, "channelRegistered:closed");
        ctx.close();
        return;
    }

    // Add (de-)serialization Handlers before this Handler
    ctx.pipeline().addBefore(ctx.name(), ObjectEncoder.class.getSimpleName(), new ObjectEncoder());
    ctx.pipeline().addBefore(ctx.name(), ObjectDecoder.class.getSimpleName(), new ObjectDecoder(
            ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader())));
    ctx.pipeline().addBefore(ctx.name(), LoggingHandler.class.getSimpleName(), new LoggingHandler(LogLevel.TRACE));

    // Timeout Handler
    ctx.pipeline().addBefore(ctx.name(), IdleStateHandler.class.getSimpleName(),
            new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    ctx.pipeline().addBefore(ctx.name(), TimeoutHandler.class.getSimpleName(), new TimeoutHandler());

    // Add exception handler
    ctx.pipeline().addLast(PipelinePlug.class.getSimpleName(), new PipelinePlug());

    super.channelRegistered(ctx);
    Log.v(TAG, "Pipeline after register: " + ctx.pipeline());
}
项目:NPush    文件:ClientInitializer.java   
@Override
  protected void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();

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

      pipeline.addLast("idleStateHandler", new IdleStateHandler(Constants.READ_IDLE_TIME, 0, Constants.ALL_IDLE_TIME, TimeUnit.SECONDS));
      // 客户端的逻辑
      pipeline.addLast("handler", new ClientHandler());
  }
项目:example    文件:MessageRecvChannelInitializer.java   
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    //ObjectDecoder的基类半包解码器LengthFieldBasedFrameDecoder的报文格式保持兼容。因为底层的父类LengthFieldBasedFrameDecoder
    //的初始化参数即为super(maxObjectSize, 0, 4, 0, 4); 
    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, MessageRecvChannelInitializer.MESSAGE_LENGTH, 0, MessageRecvChannelInitializer.MESSAGE_LENGTH));
    //利用LengthFieldPrepender回填补充ObjectDecoder消息报文头
    pipeline.addLast(new LengthFieldPrepender(MessageRecvChannelInitializer.MESSAGE_LENGTH));
    pipeline.addLast(new ObjectEncoder());
    //考虑到并发性能,采用weakCachingConcurrentResolver缓存策略。一般情况使用:cacheDisabled即可
    pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
    pipeline.addLast(new MessageRecvHandler(handlerMap));
}
项目:example    文件:MessageSendChannelInitializer.java   
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    //ObjectDecoder的基类半包解码器LengthFieldBasedFrameDecoder的报文格式保持兼容。因为底层的父类LengthFieldBasedFrameDecoder
    //的初始化参数即为super(maxObjectSize, 0, 4, 0, 4);
    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, MessageSendChannelInitializer.MESSAGE_LENGTH, 0, MessageSendChannelInitializer.MESSAGE_LENGTH));
    //利用LengthFieldPrepender回填补充ObjectDecoder消息报文头
    pipeline.addLast(new LengthFieldPrepender(MessageSendChannelInitializer.MESSAGE_LENGTH));
    pipeline.addLast(new ObjectEncoder());
    //考虑到并发性能,采用weakCachingConcurrentResolver缓存策略。一般情况使用:cacheDisabled即可
    pipeline.addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
    pipeline.addLast(new MessageSendHandler());
}
项目:netty-book    文件:SubReqClient.java   
public void connect(int port, String host) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch)
            throws Exception {
            ch.pipeline().addLast(
                new ObjectDecoder(1024, ClassResolvers
                    .cacheDisabled(this.getClass()
                        .getClassLoader())));
            ch.pipeline().addLast(new ObjectEncoder());
            ch.pipeline().addLast(new SubReqClientHandler());
        }
        });

    // 发起异步连接操作
    ChannelFuture f = b.connect(host, port).sync();

    // 当代客户端链路关闭
    f.channel().closeFuture().sync();
} finally {
    // 优雅退出,释放NIO线程组
    group.shutdownGracefully();
}
   }
项目:netty-book    文件:SubReqServer.java   
public void bind(int port) throws Exception {
// 配置服务端的NIO线程组
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 100)
        .handler(new LoggingHandler(LogLevel.INFO))
        .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) {
            ch.pipeline()
                .addLast(
                    new ObjectDecoder(
                        1024 * 1024,
                        ClassResolvers
                            .weakCachingConcurrentResolver(this
                                .getClass()
                                .getClassLoader())));
            ch.pipeline().addLast(new ObjectEncoder());
            ch.pipeline().addLast(new SubReqServerHandler());
        }
        });

    // 绑定端口,同步等待成功
    ChannelFuture f = b.bind(port).sync();

    // 等待服务端监听端口关闭
    f.channel().closeFuture().sync();
} finally {
    // 优雅退出,释放线程池资源
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
}
   }
项目:LOG735-Lab4    文件:ServerToServerConnection.java   
private void initializeConnection(){
    try {
        mClientBootStrap.group(mEventLoopGroup);
        mClientBootStrap.channel(NioSocketChannel.class);
        mClientBootStrap.option(ChannelOption.SO_KEEPALIVE, true);
        mClientBootStrap.option(ChannelOption.TCP_NODELAY, true);
        mClientBootStrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                ch.pipeline().addLast(new ObjectEncoder());
                ch.pipeline().addLast(new ServerToServerHandler());
            }
        });

        mServerToServerChannel = mClientBootStrap.connect(mRemoteAddress, Integer.parseInt(mRemotePort)).addListener(
            new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){

                    }
                }
            }
        );
    }catch(Exception e){
        e.printStackTrace();
    }
}