Example usage for io.netty.bootstrap ServerBootstrap childHandler

List of usage examples for io.netty.bootstrap ServerBootstrap childHandler

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childHandler.

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java

License:Apache License

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();

    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);//from  w  w  w  .  j  a v  a2 s. c  o m
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));

    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100),
            Constants.DEFAULT_MASTER_PORT);
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();

    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}

From source file:at.yawk.dbus.protocol.DbusConnectorTest.java

@Test(enabled = false)
public void testServer() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(EpollServerDomainSocketChannel.class);
    bootstrap.group(new EpollEventLoopGroup());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override//from w  ww  .  j  a  va  2 s.  co  m
        protected void initChannel(Channel ch) throws Exception {

            ch.pipeline().addLast(new CommandCodec()).addLast(new ChannelDuplexHandler() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof NegotiateUnixFd) {
                        ch.writeAndFlush(new Error("error"));
                    }

                    if (msg instanceof Begin) {
                        ch.pipeline().addLast(new LoggingInboundAdapter())
                                .addLast(new DbusMainProtocol(new MessageConsumer() {
                                    @Override
                                    public boolean requireAccept(MessageHeader header) {
                                        return true;
                                    }

                                    @Override
                                    public void accept(DbusMessage message) {
                                        DbusMessage response = new DbusMessage();

                                        MessageHeader header = new MessageHeader();
                                        header.setMessageType(MessageType.ERROR);
                                        header.addHeader(HeaderField.REPLY_SERIAL,
                                                BasicObject.createUint32(message.getHeader().getSerial()));
                                        //header.addHeader(HeaderField.SIGNATURE, SignatureObject.create(
                                        //        Collections.singletonList(BasicType.VARIANT)));
                                        header.addHeader(HeaderField.ERROR_NAME,
                                                BasicObject.createString("Error"));
                                        response.setHeader(header);

                                        MessageBody body = new MessageBody();
                                        //body.add(VariantObject.create(BasicObject.createString("testing!")));
                                        response.setBody(body);

                                        ch.writeAndFlush(response);
                                    }
                                }));
                        ch.pipeline().remove((Class) getClass());
                        ch.pipeline().remove(CommandCodec.class);
                    }
                }
            });
            ch.writeAndFlush(new Ok(UUID.randomUUID()));
        }
    });
    bootstrap.bind(new DomainSocketAddress(new File("test")));

    try {
        DbusUtil.callCommand(("dbus-send --address=unix:path=" + new File(".").getAbsolutePath()
                + "/test --dest=org.freedesktop.UPower --print-reply "
                + "/org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.DBus.Properties.Get string:org"
                + ".freedesktop.UPower.Device string:State").split(" "));
    } catch (Exception e) {
        e.printStackTrace();
    }
    TimeUnit.DAYS.sleep(1);
}

From source file:cn.wcl.test.netty.server.netty.NettyHttpServer.java

License:Apache License

private void init() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  w w . ja  v  a2  s.  c  om
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        b.childHandler(new HttpUploadServerInitializer(sslCtx, applicationContext, needlogin));

        Channel ch = b.bind(port).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + port + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.alibaba.dubbo.qos.server.Server.java

License:Apache License

/**
 * start server, bind port//  w w  w.ja  v a 2s. com
 */
public void start() throws Throwable {
    if (!hasStarted.compareAndSet(false, true)) {
        return;
    }
    boss = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-boss", true));
    worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(boss, worker);
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, true);
    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new QosProcessHandler(welcome, acceptForeignIp));
        }
    });
    try {
        serverBootstrap.bind(port).sync();
        logger.info("qos-server bind localhost:" + port);
    } catch (Throwable throwable) {
        logger.error("qos-server can not bind localhost:" + port, throwable);
        throw throwable;
    }
}

From source file:com.ancun.netty.httpserver.HttpServer.java

License:Apache License

public Channel bind(InetSocketAddress ipAddress) {
    ServerBootstrap bootstrap = bootstrapFactory.newServerBootstrap(getIoThreadCount());
    bootstrap.childHandler(httpServerInitializer.setMaxContentLength(serverSettings.getMaxContentSize()));

    setBootstrapOptions(bootstrap);/*  w  w w  . ja  v  a  2  s.  c om*/

    Channel channel = bootstrap.bind(ipAddress).channel();
    allChannels.add(channel);
    logger.info("netty????{}", this.getPort());

    return channel;
}

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

License:Open Source License

/**
 * startServer/*from   ww w  . j av  a2s.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();
    }
}

From source file:com.cdg.study.netty.util.NettyStartupUtil.java

License:Open Source License

public static void runServer(int port, ChannelHandler childHandler, Consumer<ServerBootstrap> block)
        throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w  w  w  .j ava 2  s  .c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(childHandler);
        block.accept(b);
        Channel ch = b.bind(port).sync().channel();
        System.err.println("Ready for 0.0.0.0:" + port);
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.cmz.http.upload.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  w  w.j  a  va 2  s  . c  o m
        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);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.farsunset.cim.sdk.server.handler.CIMNioSocketAcceptor.java

License:Apache License

public void bind() throws IOException {

    /**/*from w  w  w . j  a  v a  2  s .co m*/
     * websocket??
     */
    innerHandlerMap.put(WEBSOCKET_HANDLER_KEY, new WebsocketHandler());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {

            ch.pipeline().addLast(new ServerMessageDecoder());
            ch.pipeline().addLast(new ServerMessageEncoder());
            ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
            ch.pipeline().addLast(new IdleStateHandler(READ_IDLE_TIME, WRITE_IDLE_TIME, 0));
            ch.pipeline().addLast(CIMNioSocketAcceptor.this);
        }
    });

    bootstrap.bind(port);
}

From source file:com.fjn.helper.frameworkex.netty.v4.echotest.EchoServer.java

License:Apache License

public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w ww. java2  s.  c o m
        // Bootstraps the server
        ServerBootstrap b = new ServerBootstrap();

        // Specifies NIO transport, local socket address
        b.group(group);
        b.childGroup();
        b.channel(NioServerSocketChannel.class);
        b.localAddress(new InetSocketAddress(port));

        // Adds handler to channel pipeline
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new EchoServerHandler());
            }
        });

        // Binds server, waits for server to close, and releases resources
        ChannelFuture f = b.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }

}