Example usage for io.netty.bootstrap ServerBootstrap group

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

Introduction

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

Prototype

@Override
public ServerBootstrap group(EventLoopGroup group) 

Source Link

Document

Specify the EventLoopGroup which is used for the parent (acceptor) and the child (client).

Usage

From source file:com.flysoloing.learning.network.netty.localecho.LocalEcho.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {//w w w. ja  v  a 2  s . c o m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.github.jonbonazza.puni.core.Application.java

License:Apache License

private void bootstrap() throws Exception {
    SslContext sslContext = null;//from  w w  w. j a  v a2  s  .co m
    SSLConfiguration sslConfig = config.getSsl();
    if (config.getSsl().isEnabled()) {
        sslContext = SslContext.newServerContext(new File(sslConfig.getCert()),
                new File(sslConfig.getPrivateKey()));
    }

    EventLoopGroup eventGroup = new NioEventLoopGroup(config.getEventLoopThreadCount());

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(eventGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpInitializer(sslContext, muxer));
        Channel ch = b.bind(config.getPort()).sync().channel();
        ch.closeFuture().sync();
        bootstrapped = true;
    } finally {
        eventGroup.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.
 * //w w w .  j  ava 2s.c o 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.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   ww w  . j av  a 2  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.hxr.javatone.concurrency.netty.official.localecho.LocalEcho.java

License:Apache License

public void run() throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(port);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {/*from   w  w w . j  a v a 2 s . co m*/
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.imaginarycode.minecraft.bungeejson.impl.httpserver.NettyBootstrap.java

License:Open Source License

public void initialize() {
    group = new NioEventLoopGroup(5, factory);
    int port = 7432; // CONFIG
    ServerBootstrap b = new ServerBootstrap();
    b.group(group).channel(NioServerSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   ww  w  . j ava  2 s. c o m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("messageCodec", new HttpServerCodec());
                    pipeline.addLast("messageHandler", new HttpServerHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
    channelFuture = b.bind(port).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            BungeeJSONPlugin.getPlugin().getLogger()
                    .info("BungeeJSON server started on " + channelFuture.channel().localAddress());
        }
    });
}

From source file:com.outbrain.pajamasproxy.memcached.server.MemCacheDaemon.java

License:Apache License

private void createBootstratp() {
    log.info("Initializing TCP...");
    ServerBootstrap tcpBootstrap = new ServerBootstrap();
    tcpBootstrap.group(eventLoopGroup);
    tcpBootstrap.channel(NioServerSocketChannel.class);
    tcpBootstrap.childHandler(serverPipelineFactory);

    final ChannelFuture channelFuture = tcpBootstrap.bind(addr).addListener(new ChannelFutureListener() {
        @Override/*w  w  w.j av a2  s. c  o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            log.info("Server started; listening to {}", addr);
            running = true;
        }
    });
}

From source file:com.relayrides.pushy.apns.MockApnsServer.java

License:Open Source License

public synchronized void start() throws InterruptedException {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    final MockApnsServer server = this;

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

        @Override//from w  w w  .j ava2 s. c o  m
        protected void initChannel(final SocketChannel channel) throws Exception {
            channel.pipeline().addLast("ssl", new SslHandler(SSLTestUtil.createSSLEngineForMockServer()));
            channel.pipeline().addLast("encoder", new ApnsErrorEncoder());
            channel.pipeline().addLast("decoder", new ApnsPushNotificationDecoder());
            channel.pipeline().addLast("handler", new MockApnsServerHandler(server));
        }
    });

    this.channel = bootstrap.bind(this.port).await().channel();
}

From source file:com.relayrides.pushy.apns.MockFeedbackServer.java

License:Open Source License

public synchronized void start() throws InterruptedException {
    final ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(this.eventLoopGroup);
    bootstrap.channel(NioServerSocketChannel.class);

    final MockFeedbackServer server = this;
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override// w w  w  . j av  a2s  . c om
        protected void initChannel(final SocketChannel channel) throws Exception {
            channel.pipeline().addLast("ssl", new SslHandler(SSLTestUtil.createSSLEngineForMockServer()));
            channel.pipeline().addLast("encoder", new ExpiredTokenEncoder());
            channel.pipeline().addLast("handler", new MockFeedbackServerHandler(server));
        }
    });

    this.channel = bootstrap.bind(this.port).await().channel();
}

From source file:com.springapp.mvc.netty.example.localecho.LocalEcho.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);

    EventLoopGroup serverGroup = new LocalEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {//from www  .  j  a  v a 2 s. c  o  m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}