Example usage for io.netty.bootstrap ServerBootstrap ServerBootstrap

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

Introduction

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

Prototype

public ServerBootstrap() 

Source Link

Usage

From source file:com.github.nettybook.ch8.TelnetServer.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  . ja va2 s .com*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new TelnetServerInitializer());

        b.bind(listenPort).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.rmannibucau.featuredmock.http.DefaultFeaturedHttpServer.java

License:Apache License

@Override
public FeaturedHttpServer start() {
    workerGroup = new NioEventLoopGroup(threads, new FeaturedThreadFactory());

    try {/*from   w ww .  j  ava  2 s  .co  m*/
        final ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_SNDBUF, 1024)
                .option(ChannelOption.TCP_NODELAY, true).group(workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new FeaturedChannelInitializer(mappers, engine)).bind(host, port)
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            LOGGER.severe("Can't start HTTP server");
                        } else {
                            LOGGER.info(String.format("Server started on http://%s:%s", host, port));
                        }
                    }
                }).sync();
    } catch (final InterruptedException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

    return this;
}

From source file:com.github.sinsinpub.pero.frontend.NettySocksServer.java

License:Apache License

public void run() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1, ThreadFactoryRepository.BOSS_GORUP);
    EventLoopGroup workerGroup = new NioEventLoopGroup(getMaxWorkerThreads(),
            ThreadFactoryRepository.WORKER_GROUP);
    try {//from ww  w.j a  v a  2  s  . c  om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(getSocksServerInitializer());
        ChannelFuture cf = b.bind(getPort()).sync();
        logger.info(
                String.format("Proxy server %s %s started.", ApplicationVersion.DEFAULT.getApplicationName(),
                        ApplicationVersion.DEFAULT.getApplicationVersion()));
        cf.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.sinsinpub.pero.manual.proxyhandler.ProxyServer.java

License:Apache License

/**
 * Starts a new proxy server with disabled authentication for testing purpose.
 * //from w w w. jav  a  2  s.co  m
 * @param useSsl {@code true} if and only if implicit SSL is enabled
 * @param testMode the test mode
 * @param username the expected username. If the client tries to authenticate with a different
 *            username, this server will fail the authentication request.
 * @param password the expected password. If the client tries to authenticate with a different
 *            password, this server will fail the authentication request.
 * @param destination the expected destination. If the client requests proxying to a different
 *            destination, this server will reject the connection request.
 */
protected ProxyServer(final boolean useSsl, TestMode testMode, InetSocketAddress destination, String username,
        String password, int bindPort, boolean logging) {

    this.testMode = testMode;
    this.destination = destination;
    this.username = username;
    this.password = password;

    ServerBootstrap b = new ServerBootstrap();
    b.channel(NioServerSocketChannel.class);
    if (logging) {
        b.handler(new LoggingHandler(LogLevel.INFO));
    }
    b.group(StaticContextProvider.group);
    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (useSsl) {
                p.addLast(StaticContextProvider.serverSslCtx.newHandler(ch.alloc()));
            }

            configure(ch);
        }
    });

    ch = (ServerSocketChannel) b.bind(NetUtil.LOCALHOST, bindPort).syncUninterruptibly().channel();
}

From source file:com.github.sparkfy.network.server.TransportServer.java

License:Apache License

private void init(String hostToBind, int portToBind) {

    IOMode ioMode = IOMode.valueOf(conf.ioMode());
    EventLoopGroup bossGroup = NettyUtils.createEventLoop(ioMode, conf.serverThreads(), "shuffle-server");
    EventLoopGroup workerGroup = bossGroup;

    PooledByteBufAllocator allocator = NettyUtils.createPooledByteBufAllocator(conf.preferDirectBufs(),
            true /* allowCache */, conf.serverThreads());

    bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NettyUtils.getServerChannelClass(ioMode)).option(ChannelOption.ALLOCATOR, allocator)
            .childOption(ChannelOption.ALLOCATOR, allocator);

    if (conf.backLog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, conf.backLog());
    }//from  www. j  a  v  a2s  . c o  m

    if (conf.receiveBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }

    if (conf.sendBuf() > 0) {
        bootstrap.childOption(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            RpcHandler rpcHandler = appRpcHandler;
            for (TransportServerBootstrap bootstrap : bootstraps) {
                rpcHandler = bootstrap.doBootstrap(ch, rpcHandler);
            }
            context.initializePipeline(ch, rpcHandler);
        }
    });

    InetSocketAddress address = hostToBind == null ? new InetSocketAddress(portToBind)
            : new InetSocketAddress(hostToBind, portToBind);
    channelFuture = bootstrap.bind(address);
    channelFuture.syncUninterruptibly();

    port = ((InetSocketAddress) channelFuture.channel().localAddress()).getPort();
    logger.debug("Shuffle server started on port :" + port);
}

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Initializes the server, socket, and channel.
 *
 * @param loopGroup          The event loop group.
 * @param serverChannelClass The socket channel class.
 * @throws InterruptedException on interruption.
 *//*from w w  w.  j  a v a2  s  .c o  m*/
private void start(final EventLoopGroup loopGroup, final Class<? extends ServerChannel> serverChannelClass)
        throws InterruptedException {

    try {
        final InetSocketAddress inet = new InetSocketAddress(port);

        final ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.option(ChannelOption.SO_REUSEADDR, true);
        b.option(ChannelOption.SO_LINGER, 0);
        b.group(loopGroup).channel(serverChannelClass).childHandler(new WebServerInitializer());
        b.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        b.childOption(ChannelOption.SO_REUSEADDR, true);

        // final Channel ch = b.bind(inet).sync().channel();
        // ch.closeFuture().sync();
        b.bind(inet);
        logger.info("Listening for Admin on {}", inet);
    } catch (Throwable t) {
        logger.warn(t.getMessage(), t);
    } finally {
        // loopGroup.shutdownGracefully().sync();
    }
}

From source file:com.github.unafraid.signer.server.ServerManager.java

License:Apache License

private void init() {
    SslContext sslCtx = null;//from   ww w . jav  a 2 s .c o  m
    if (SSL) {
        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate("localhost");
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } catch (Exception e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }

    InetAddress listenAddress;
    try {
        listenAddress = Inet4Address.getByName(HOSTNAME);
    } catch (Exception e) {
        LOGGER.warn("Incorrect listen ip specified: {} using localhost instead!", HOSTNAME);
        listenAddress = Inet4Address.getLoopbackAddress();
    }
    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        final ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerInitializer(sslCtx));

        // Start listening
        final Channel ch = b.bind(listenAddress, PORT).sync().channel();

        LOGGER.info("Open your web browser and navigate to {}://{}{}/", (SSL ? "https" : "http"),
                listenAddress.getHostAddress(), (PORT != 443 && PORT != 80 ? ":" + PORT : ""));

        // Block til closed
        ch.closeFuture().sync();

    } catch (Exception e) {
        LOGGER.warn("Failed to initialize server: ", e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java

License:Open Source License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w ww  .  jav a  2s  . c om*/
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

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

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.github.wangshuwei5.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO// w  w  w. ja  v a  2 s . c  o m
    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 NettyServerInitializer(SSLMODE.CSA.toString()));

        // ???
        ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

        // ???
        f.channel().closeFuture().sync();

        System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.wolf480pl.ircd.netty.NettyServer.java

License:Open Source License

public ChannelFuture start() {
    if (!started.compareAndSet(false, true)) {
        return null;
    }//from w  w  w  .j a  v a  2  s  .  c  o m

    ServerBootstrap bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();

    IRCChannelInitializer initializer = new IRCChannelInitializer(handler);

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(initializer)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture future = bootstrap.bind(bindAddress);
    this.channel = future.channel();
    return future;
}