Example usage for io.netty.channel.socket.nio NioSocketChannel pipeline

List of usage examples for io.netty.channel.socket.nio NioSocketChannel pipeline

Introduction

In this page you can find the example usage for io.netty.channel.socket.nio NioSocketChannel pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline .

Usage

From source file:com.addthis.meshy.Meshy.java

License:Apache License

protected Meshy() {
    if (HOSTNAME != null) {
        uuid = HOSTNAME + "-" + Long.toHexString(System.currentTimeMillis() & 0xffffff);
    } else {/*  ww w  . ja  va  2 s . c  o m*/
        uuid = Long.toHexString(UUID.randomUUID().getMostSignificantBits());
    }
    workerGroup = new NioEventLoopGroup();
    clientBootstrap = new Bootstrap().option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK).channel(NioSocketChannel.class)
            .group(workerGroup).handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(Meshy.this, ch));
                }
            });
    updateLastEventTime();
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();//ww w. j  ava 2  s  . co  m
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.alibaba.dubbo.remoting.transport.netty.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    //netty4/*from  ww w. j a va2 s . c o  m*/
    bootstrap = new ServerBootstrap();
    //1?
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    //       cpu*2 
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            //                
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();

    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override//  w w w  .ja  v  a  2 s. co m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.baidu.rigel.biplatform.ma.file.client.monitor.FileServerMonitor.java

License:Open Source License

/**
 * ?/*from   w  w w. j  av  a  2  s  .  c  o  m*/
 */
public void start() throws Exception {
    EventLoopGroup work = new NioEventLoopGroup();
    Bootstrap strap = new Bootstrap();
    try {
        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(1024,
                                ClassResolvers.cacheDisabled(FileServerMonitor.class.getClassLoader())));
                        chl.pipeline().addLast(new ObjectEncoder());
                        chl.pipeline().addLast(new FileServerMonitor());
                    }

                });

        ChannelFuture future = strap.connect(new InetSocketAddress(host, port));
        future.channel().closeFuture().sync();
    } finally {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                    ChannelFuture future = strap.connect("localhost", 9090).sync();
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
            }

        });
    }
}

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

License:Open Source License

/**
 * ?/* w  w w.j  a v  a  2 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.dinstone.netty.Client.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {

                @Override//  www.  j  a  v a  2 s . c o m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("dd", new ChannelHandlerAdapter() {

                        /**
                         * {@inheritDoc}
                         * 
                         * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext,
                         *      java.lang.Throwable)
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            System.out.println("error: ");
                            cause.printStackTrace();
                        }
                    });
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
            }
        }
    });
}

From source file:com.dinstone.netty.Server.java

License:Apache License

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

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, true).childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*from   w w w. ja v a2s  . c  o  m*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new SimpleServerHandler());
                }
            });
    b.bind(8090).sync().channel().closeFuture().sync();
}

From source file:com.friz.audio.AudioServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    AudioServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override/*from  w w w  .  j  av  a  2s . c om*/
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
                    p.addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(65536));
                    p.addLast(ChunkedWriteHandler.class.getName(), new ChunkedWriteHandler());
                    p.addLast(AudioChannelHandler.class.getName(), new AudioChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);

    hub.listen(AudioRequestEvent.class, new AudioRequestEventListener());

    service.startAsync();
}

From source file:com.friz.game.GameServer.java

License:Open Source License

@Override
public void initialize() {
    group = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    bootstrap = new ServerBootstrap();

    GameServer s = this;

    bootstrap.group(group).channel(NioServerSocketChannel.class)
            //.handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from  w  ww. ja v a2  s  .  c  o m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(LoginInitEncoder.class.getName(), new LoginInitEncoder());
                    p.addLast(LoginInitDecoder.class.getName(), new LoginInitDecoder());
                    p.addLast(GameChannelHandler.class.getName(), new GameChannelHandler(s));
                }

            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.TCP_NODELAY, true);
}