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.twitter.http2.HttpHeaderCompressionTest.java

License:Apache License

private void testHeaderEcho(HttpHeaderBlockFrame frame) throws Throwable {
    final EchoHandler sh = new EchoHandler();
    final TestHandler ch = new TestHandler(frame);

    ServerBootstrap sb = new ServerBootstrap().group(new LocalEventLoopGroup())
            .channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {
                @Override// ww  w .  j  a va 2 s  . com
                public void initChannel(LocalChannel channel) throws Exception {
                    channel.pipeline().addLast(new HttpConnectionHandler(true), sh);
                }
            });
    Bootstrap cb = new Bootstrap().group(new LocalEventLoopGroup()).channel(LocalChannel.class)
            .handler(new ChannelInitializer<LocalChannel>() {
                @Override
                public void initChannel(LocalChannel channel) throws Exception {
                    channel.pipeline().addLast(new HttpConnectionHandler(false), ch);
                }
            });

    LocalAddress localAddress = new LocalAddress("HttpHeaderCompressionTest");
    Channel sc = sb.bind(localAddress).sync().channel();
    ChannelFuture ccf = cb.connect(localAddress);
    assertTrue(ccf.awaitUninterruptibly().isSuccess());

    while (!ch.success) {
        if (sh.exception.get() != null) {
            break;
        }
        if (ch.exception.get() != null) {
            break;
        }

        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            // Ignore.
        }
    }

    sc.close().awaitUninterruptibly();
    cb.group().shutdownGracefully();
    sb.group().shutdownGracefully();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
        throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
        throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
        throw ch.exception.get();
    }
}

From source file:com.twocater.diamond.core.netty.NettyConnector.java

@Override
public void bind() throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup);
    ChannelHandlerAdapter serverHandler = this.nettyHandlerFactory.createServerHandler();
    if (serverHandler != null) {
        serverBootstrap.handler(serverHandler);
    }//from www  .  ja  v  a2  s.  com
    serverBootstrap.channel(NioServerSocketChannel.class);
    serverBootstrap.childHandler(this.nettyHandlerFactory.createChildHandler(connectorConfig.getTimeout()));

    serverBootstrap.option(ChannelOption.SO_BACKLOG, connectorConfig.getSo_backlog_parent());
    serverBootstrap.option(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr_parent());

    //         serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);//??? netty
    //        serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 5000);//??? ?timeout??
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, connectorConfig.isTcp_nodelay());
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, connectorConfig.isKeepAlive());

    serverBootstrap.childOption(ChannelOption.SO_REUSEADDR, connectorConfig.isSo_reuseaddr());
    serverBootstrap.childOption(ChannelOption.SO_LINGER, connectorConfig.getSo_linger());
    serverBootstrap.childOption(ChannelOption.SO_SNDBUF, connectorConfig.getSo_sndbuf());
    serverBootstrap.childOption(ChannelOption.SO_RCVBUF, connectorConfig.getSo_rcvbuf());

    channelFuture = serverBootstrap.bind(connectorConfig.getPort()).sync();
}

From source file:com.twocater.diamond.core.test.DiscardServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w ww .  j av  a  2 s.c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DiscardServerHandler());
            }
        });
        b.option(ChannelOption.SO_BACKLOG, 128);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();
        System.out.println("bind");
        f.channel().closeFuture().sync();
        System.out.println("close");
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.twocater.diamond.core.test.HttpHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = null;
    //        if (SSL) {
    //            SelfSignedCertificate ssc = new SelfSignedCertificate();
    //            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    //        } else {
    //            sslCtx = null;
    //        }//from   w  ww .  j a va  2 s.  co m

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(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.util.MyServer.java

License:Apache License

/**
 * It is a standard server object//from  w  ww.  j  a v  a 2 s .com
 * @param serverType  
 * @param logger message logger
 */
public MyServer(int serverType, Logger logger) {
    bootStrap = new ServerBootstrap();
    workerGroup = new NioEventLoopGroup();
    this.logger = logger;
    if (serverType == ACCEPT_MULTI_CONNECTION) {
        bossGroup = new NioEventLoopGroup();
        bootStrap.group(bossGroup, workerGroup);
    } else
        bootStrap.group(workerGroup);
    bootStrap.channel(NioServerSocketChannel.class);
}

From source file:com.vela.iot.active.netty.http2.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {// ww w  .  java2  s. c  o m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /*
                * NOTE: the cipher filter may not include all ciphers
                * required by the HTTP/2 specification. Please refer to the
                * HTTP/2 specification for cipher requirements.
                */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(7);
    try {
        LastInboundHandler serverLastInboundHandler = new SharableLastInboundHandler();
        ServerBootstrap b = new ServerBootstrap();
        // BACKLOG?ServerSocket?????1Java50
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new Http2Codec(true, serverLastInboundHandler));
                        //p.addLast(new HttpContentCompressor(1));
                        p.addLast(new HelloWorldHttp2HandlerBuilder().build());
                    }
                });

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

        System.err.println("Open your HTTP/2-enabled 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.vethrfolnir.game.network.MuNetworkServer.java

License:Open Source License

@Inject
private void load() {

    log.info("Preparing Game server listening! Info[Host: " + host + ", Port: " + port + "]");
    try {//w ww .j  av  a 2s. c  o m
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MuCyperDecoder(), new MuChannelHandler()
                        //new MuCyperEncoder()
                        );
                    }
                });
    } catch (Exception e) {
        log.fatal("Unable to set up netty!", e);
    }
}

From source file:com.vethrfolnir.login.network.NetworkClientServer.java

License:Open Source License

@Inject
private void load() {
    log.info("Preparing Client server listening! Info[Host: " + host + ", Port: " + port + "]");
    try {/*from   w  w w. j a va  2  s .co  m*/
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                //new LoggingHandler(LogLevel.INFO)
                                new ClientChannelHandler());
                    }
                });
    } catch (Exception e) {
        log.fatal("Unable to set up netty!", e);
    }
}

From source file:com.vethrfolnir.login.network.NetworkGameServer.java

License:Open Source License

@Inject
private void load() {
    log.info("Preparing Game server listening! Info[Host: " + host + ", Port: " + port + "]");
    try {//from  w w  w  .  j ava  2  s.  c  o m
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                //new LoggingHandler(LogLevel.INFO)
                                new GameChannelHandler(NetworkGameServer.this));
                    }
                });
    } catch (Exception e) {
        log.fatal("Unable to set up netty!", e);
    }
}

From source file:com.vexsoftware.votifier.NuVotifierBukkit.java

License:Open Source License

@Override
public void onEnable() {
    NuVotifierBukkit.instance = this;

    // Set the plugin version.
    version = getDescription().getVersion();

    if (!getDataFolder().exists()) {
        getDataFolder().mkdir();/*  www  .j  a va 2  s .  c  o  m*/
    }

    // Handle configuration.
    File config = new File(getDataFolder() + "/config.yml");
    YamlConfiguration cfg;
    File rsaDirectory = new File(getDataFolder() + "/rsa");

    /*
     * Use IP address from server.properties as a default for
     * configurations. Do not use InetAddress.getLocalHost() as it most
     * likely will return the main server address instead of the address
     * assigned to the server.
     */
    String hostAddr = Bukkit.getServer().getIp();
    if (hostAddr == null || hostAddr.length() == 0)
        hostAddr = "0.0.0.0";

    /*
     * Create configuration file if it does not exists; otherwise, load it
     */
    if (!config.exists()) {
        try {
            // First time run - do some initialization.
            getLogger().info("Configuring Votifier for the first time...");

            // Initialize the configuration file.
            config.createNewFile();

            // Load and manually replace variables in the configuration.
            String cfgStr = new String(ByteStreams.toByteArray(getResource("bukkitConfig.yml")),
                    StandardCharsets.UTF_8);
            String token = TokenUtil.newToken();
            cfgStr = cfgStr.replace("%default_token%", token).replace("%ip%", hostAddr);
            Files.write(cfgStr, config, StandardCharsets.UTF_8);

            /*
             * Remind hosted server admins to be sure they have the right
             * port number.
             */
            getLogger().info("------------------------------------------------------------------------------");
            getLogger()
                    .info("Assigning NuVotifier to listen on port 8192. If you are hosting Craftbukkit on a");
            getLogger().info("shared server please check with your hosting provider to verify that this port");
            getLogger().info("is available for your use. Chances are that your hosting provider will assign");
            getLogger().info("a different port, which you need to specify in config.yml");
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Your default NuVotifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        } catch (Exception ex) {
            getLogger().log(Level.SEVERE, "Error creating configuration file", ex);
            gracefulExit();
            return;
        }
    }

    // Load configuration.
    cfg = YamlConfiguration.loadConfiguration(config);

    /*
     * Create RSA directory and keys if it does not exist; otherwise, read
     * keys.
     */
    try {
        if (!rsaDirectory.exists()) {
            rsaDirectory.mkdir();
            keyPair = RSAKeygen.generate(2048);
            RSAIO.save(rsaDirectory, keyPair);
        } else {
            keyPair = RSAIO.load(rsaDirectory);
        }
    } catch (Exception ex) {
        getLogger().log(Level.SEVERE, "Error reading configuration file or RSA tokens", ex);
        gracefulExit();
        return;
    }

    debug = cfg.getBoolean("debug", false);

    boolean setUpPort = cfg.getBoolean("enableExternal", true); //Always default to running the external port

    if (setUpPort) {
        // Load Votifier tokens.
        ConfigurationSection tokenSection = cfg.getConfigurationSection("tokens");

        if (tokenSection != null) {
            Map<String, Object> websites = tokenSection.getValues(false);
            for (Map.Entry<String, Object> website : websites.entrySet()) {
                tokens.put(website.getKey(), KeyCreator.createKeyFrom(website.getValue().toString()));
                getLogger().info("Loaded token for website: " + website.getKey());
            }
        } else {
            String token = TokenUtil.newToken();
            tokenSection = cfg.createSection("tokens");
            tokenSection.set("default", token);
            tokens.put("default", KeyCreator.createKeyFrom(token));
            try {
                cfg.save(config);
            } catch (IOException e) {
                getLogger().log(Level.SEVERE, "Error generating Votifier token", e);
                gracefulExit();
                return;
            }
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("No tokens were found in your configuration, so we've generated one for you.");
            getLogger().info("Your default Votifier token is " + token + ".");
            getLogger().info("You will need to provide this token when you submit your server to a voting");
            getLogger().info("list.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        // Initialize the receiver.
        final String host = cfg.getString("host", hostAddr);
        final int port = cfg.getInt("port", 8192);
        if (debug)
            getLogger().info("DEBUG mode enabled!");

        final boolean disablev1 = cfg.getBoolean("disable-v1-protocol");
        if (disablev1) {
            getLogger().info("------------------------------------------------------------------------------");
            getLogger().info("Votifier protocol v1 parsing has been disabled. Most voting websites do not");
            getLogger().info("currently support the modern Votifier protocol in NuVotifier.");
            getLogger().info("------------------------------------------------------------------------------");
        }

        serverGroup = new NioEventLoopGroup(1);

        new ServerBootstrap().channel(NioServerSocketChannel.class).group(serverGroup)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.attr(VotifierSession.KEY).set(new VotifierSession());
                        channel.attr(VotifierPlugin.KEY).set(NuVotifierBukkit.this);
                        channel.pipeline().addLast("greetingHandler", new VotifierGreetingHandler());
                        channel.pipeline().addLast("protocolDifferentiator",
                                new VotifierProtocolDifferentiator(false, !disablev1));
                        channel.pipeline().addLast("voteHandler",
                                new VoteInboundHandler(NuVotifierBukkit.this));
                    }
                }).bind(host, port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            serverChannel = future.channel();
                            getLogger()
                                    .info("Votifier enabled on socket " + serverChannel.localAddress() + ".");
                        } else {
                            SocketAddress socketAddress = future.channel().localAddress();
                            if (socketAddress == null) {
                                socketAddress = new InetSocketAddress(host, port);
                            }
                            getLogger().log(Level.SEVERE, "Votifier was not able to bind to " + socketAddress,
                                    future.cause());
                        }
                    }
                });
    } else {
        getLogger().info(
                "You have enableExternal set to false in your config.yml. NuVotifier will NOT listen to votes coming in from an external voting list.");
    }

    ConfigurationSection forwardingConfig = cfg.getConfigurationSection("forwarding");
    if (forwardingConfig != null) {
        String method = forwardingConfig.getString("method", "none").toLowerCase(); //Default to lower case for case-insensitive searches
        if ("none".equals(method)) {
            getLogger().info(
                    "Method none selected for vote forwarding: Votes will not be received from a forwarder.");
        } else if ("pluginmessaging".equals(method)) {
            String channel = forwardingConfig.getString("pluginMessaging.channel", "NuVotifier");
            try {
                forwardingMethod = new BukkitPluginMessagingForwardingSink(this, channel, this);
                getLogger().info("Receiving votes over PluginMessaging channel '" + channel + "'.");
            } catch (RuntimeException e) {
                getLogger().log(Level.SEVERE,
                        "NuVotifier could not set up PluginMessaging for vote forwarding!", e);
            }
        } else {
            getLogger().severe(
                    "No vote forwarding method '" + method + "' known. Defaulting to noop implementation.");
        }
    }
}