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:com.yahoo.pulsar.client.api.MockBrokerService.java

License:Apache License

public void startMockBrokerService() throws Exception {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
    final int numThreads = 2;

    final int MaxMessageSize = 5 * 1024 * 1024;
    EventLoopGroup eventLoopGroup;//from w  ww  . j  a v a  2  s.c  o m

    try {
        if (SystemUtils.IS_OS_LINUX) {
            try {
                eventLoopGroup = new EpollEventLoopGroup(numThreads, threadFactory);
            } catch (UnsatisfiedLinkError e) {
                eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
            }
        } else {
            eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
        }
        workerGroup = eventLoopGroup;

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup, workerGroup);
        if (workerGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("frameDecoder",
                        new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                ch.pipeline().addLast("handler", new MockServerCnx());
            }
        });
        // Bind and start to accept incoming connections.
        bootstrap.bind(brokerServicePort).sync();
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.yahoo.pulsar.discovery.service.DiscoveryService.java

License:Apache License

/**
 * starts server to handle discovery-request from client-channel
 * //  ww  w  . ja v a 2 s.co m
 * @throws Exception
 */
public void startServer() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        bootstrap.channel(NioServerSocketChannel.class);
    }

    bootstrap.childHandler(new ServiceChannelInitializer(this, config, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(config.getServicePort()).sync();
    LOG.info("Started Pulsar Broker service on port {}", config.getWebServicePort());

    if (config.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new ServiceChannelInitializer(this, config, true));
        tlsBootstrap.bind(config.getServicePortTls()).sync();
        LOG.info("Started Pulsar Broker TLS service on port {}", config.getWebServicePortTls());
    }
}

From source file:com.zaradai.distributor.messaging.netty.NettyServer.java

License:Apache License

private ServerBootstrap createBootstrap() {
    ServerBootstrap res = new ServerBootstrap()
            .group(eventLoopGroups.getServerGroup(), eventLoopGroups.getClientGroup())
            .channel(NioServerSocketChannel.class);
    configure(res);//ww  w.j  av  a2  s  .co  m
    res.childHandler(createClientInitializer());

    return res;
}

From source file:com.zextras.modules.chat.server.xmpp.netty.ChatXmppService.java

License:Open Source License

private ServerBootstrap buildBoostrap(EventLoopGroup acceptorGroup, EventLoopGroup workerGroup,
        final SSLContext zimbraSSLContext, final boolean oldSSL) {

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(acceptorGroup, workerGroup);

    serverBootstrap.channel(NioServerSocketChannel.class);

    ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
        @Override// ww  w.  j  a va2s.  c  o m
        public void initChannel(SocketChannel ch) throws Exception {
            try {
                if (oldSSL) {
                    final SSLEngine engine = zimbraSSLContext.createSSLEngine();
                    engine.setUseClientMode(false);
                    ch.pipeline().addFirst(null, "SSL", new SslHandler(engine, false));
                }

                ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer());
                FirstTags firstTagsHandler = new FirstTags(mXmppHandlerFactory, mEventManager, ch,
                        mSchemaProvider, zimbraSSLContext, oldSSL, mChatProperties, mNettyService,
                        mProxyAuthRequestEncoder, mXmppEventFilter, mXmppFilterOut);
                ch.pipeline().addAfter("SubTagTokenizer", "FirstTags", firstTagsHandler);
            } catch (Throwable ex) {
                ChatLog.log.warn("Unable to initialize XMPP connection: " + Utils.exceptionToString(ex));
                ch.close();
            }
        }
    };

    serverBootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0);

    return serverBootstrap;
}

From source file:com.zextras.modules.chat.services.LocalXmppService.java

License:Open Source License

@Override
public void run() {
    ChatLog.log.info("Listening on port " + DEFAULT_LOCAL_XMPP_PORT);
    EventLoopGroup acceptorGroup = new NioEventLoopGroup(4);
    EventLoopGroup channelWorkerGroup = new NioEventLoopGroup(8);

    Channel channel;/*ww  w  .  j  a  v  a 2 s.co m*/
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptorGroup, channelWorkerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        ChannelHandler handler = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                try {
                    SSLEngine sslEngine = mZimbraSSLContextProvider.get().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    SslHandler sslHandler = new SslHandler(sslEngine);
                    ch.pipeline().addFirst("ssl", sslHandler);
                    ch.pipeline().addLast(null, "SubTagTokenizer", new XmlSubTagTokenizer());
                    ch.pipeline().addLast(null, "XmlTagTokenizer", new XmlTagTokenizer());
                    ch.pipeline().addAfter("XmlTagTokenizer", "StanzaProcessor",
                            new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                    mLocalXmppReceiver.processStanza((String) msg);
                                }
                            });
                } catch (Throwable t) {
                    ChatLog.log.warn("Unable to initializer XMPP connection: " + Utils.exceptionToString(t));
                    ch.close();
                }
            }
        };

        ChannelFuture channelFuture = bootstrap.childHandler(handler).option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 0).bind(DEFAULT_LOCAL_XMPP_PORT).sync();

        if (!channelFuture.isSuccess()) {
            throw channelFuture.cause();
        }

        channel = channelFuture.channel();
        mInitializationPromise.setSuccess(null);
    } catch (Throwable e) {
        mInitializationPromise.setFailure(e);
        return;
    }

    mLock.lock();
    try {
        while (!mStopRequested) {
            try {
                mWaitStopRequest.await();
            } catch (InterruptedException ignored) {
            }
        }

        channel.close().sync();

        acceptorGroup.shutdownGracefully().sync();
        channelWorkerGroup.shutdownGracefully().sync();
    } catch (InterruptedException ignored) {
    } finally {
        mLock.unlock();
    }
}

From source file:com.zhucode.longio.transport.netty.NettyConnector.java

License:Open Source License

private void runOneHttpServer(int port, Dispatcher dispatcher, ProtocolType pt) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);/*w ww  .  j  av  a2 s.  co m*/
    b.channel(NioServerSocketChannel.class);

    b.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new HttpServerCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(65536));
            ch.pipeline().addLast(new IdleStateHandler(6000, 3000, 0));
            ch.pipeline().addLast(new HttpHandler(NettyConnector.this, dispatcher, callbackDispatcher,
                    getProtocolParser(pt)));
        }

    });
    b.option(ChannelOption.SO_BACKLOG, 4096);

    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f;
    try {
        f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.zhucode.longio.transport.netty.NettyConnector.java

License:Open Source License

private void runOneRawSocketServer(int port, Dispatcher dispatcher, ProtocolType pt) {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup);//from ww  w  . j  ava 2s.c o m
    b.channel(NioServerSocketChannel.class);

    b.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
            ch.pipeline().addLast("encoder", new LengthFieldPrepender(2, false));
            ch.pipeline().addLast(new IdleStateHandler(6000, 3000, 0));
            ch.pipeline().addLast(new RawSocketHandler(NettyConnector.this, dispatcher, callbackDispatcher,
                    getProtocolParser(pt)));
        }

    });
    b.option(ChannelOption.SO_BACKLOG, 4096);

    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture f;
    try {
        f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:controlspy3.ControlSpy3.java

public void run() {

    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from   ww  w .  j av  a2 s  .  c o  m
        // Server
        ServerBootstrap boots = new ServerBootstrap();
        boots.group(bossGroup, workerGroup);
        boots.channel(NioServerSocketChannel.class);
        boots.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new TimeEncoder(), new SpyAsServer());
                if (ALGO == false) {
                    System.out.println("se salio ");
                }
                System.out.println("Cliente conectado!");
            }
        }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        //SERVER
        // Bind and start to accept incoming connections.
        ChannelFuture future_ch = boots.bind(port).sync();

        //SERVER
        // Wait until the server socket is closed. Server
        future_ch.channel().closeFuture().sync();

    } catch (InterruptedException ex) {

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

From source file:de.pvsnp.chat.api.connector.ChatServer.java

public void connect() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup(); // (1)

    try {//w  w  w  .j a  v  a 2  s .  c o m
        ServerBootstrap bootstrap = new ServerBootstrap(); // (2)
        bootstrap.group(bossGroup, workerGroup); // (3)
        bootstrap.channel(NioServerSocketChannel.class);// (4)
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { // 5
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                System.out.println(
                        "Ein Computer hat sich verbunden. IP: " + channel.remoteAddress().getHostName()); // (6)
                channel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")), // (2)
                        new LineBasedFrameDecoder(1024), // (3)
                        new StringDecoder(Charset.forName("UTF-8")), // (2)
                        new EchoServerHandler());
                c.add(channel);
                sendMassage(channel);
            }
        });// (7)
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, keepalive); // (8)
        ChannelFuture future = bootstrap.bind(port).sync(); // (9)
        System.out.println("Server gestartet!");
        future.channel().closeFuture().sync(); // (10)
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully(); // (11)
        workerGroup.shutdownGracefully(); // (11)
    }
}

From source file:dpfmanager.shell.modules.server.core.HttpServer.java

License:Open Source License

public void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from  w  ww .  j  av  a 2 s . c om*/
        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 HttpServerInitializer(sslCtx, context));

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

        context.send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG,
                DPFManagerProperties.getBundle().getString("startedServer").replace("%1", getServerUri()),
                true));

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