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.spotify.netty4.handler.codec.zmtp.ProtocolViolationTests.java

License:Apache License

@Before
public void setup() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(NioServerSocketChannel.class);
    bossGroup = new NioEventLoopGroup(1);
    group = new NioEventLoopGroup();
    serverBootstrap.group(bossGroup, group);
    serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override//  w  w w  . j  av a  2s  .c om
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(
                    ZMTPCodec.builder().protocol(ZMTP20).socketType(ROUTER).localIdentity(identity).build(),
                    mockHandler);
        }
    });

    serverChannel = serverBootstrap.bind(new InetSocketAddress("localhost", 0)).awaitUninterruptibly()
            .channel();
    serverAddress = (InetSocketAddress) serverChannel.localAddress();
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPSocket.java

License:Apache License

/**
 * Bind this socket to an address.//from   ww w. j a va  2  s .  co m
 */
public ListenableFuture<InetSocketAddress> bind(final InetSocketAddress address) {
    final ServerBootstrap b = new ServerBootstrap().channel(NioServerSocketChannel.class).group(GROUP)
            .childHandler(new ChannelInitializer());
    final ChannelFuture f = b.bind(address);
    channelGroup.add(f.channel());
    if (closed) {
        f.channel().close();
        return immediateFailedFuture(new ClosedChannelException());
    }
    return transform(listenable(f), new Function<Void, InetSocketAddress>() {
        @Override
        public InetSocketAddress apply(final Void input) {
            return (InetSocketAddress) f.channel().localAddress();
        }
    });
}

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  w  w w  . ja va 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.springapp.mvc.netty.example.spdy.server.SpdyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .applicationProtocolConfig(/* w  w  w  . jav  a2  s  .c o m*/
                    new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()))
            .build();

    // 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 SpdyServerInitializer(sslCtx));

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

        System.err
                .println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

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

From source file:com.srotya.linea.network.InternalTCPTransportServer.java

License:Apache License

public void init() throws Exception {
    final SslContext sslCtx;
    if (SSL) {/*from  w  ww .  ja  v a 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(1);

    ServerBootstrap b = new ServerBootstrap();
    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();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new KryoObjectEncoder());
                    p.addLast(new KryoObjectDecoder());
                    p.addLast(new IWCHandler(null)); //TODO add router
                }

            }).bind(Inet4Address.getByName("localhost"), 9999).sync().channel().closeFuture().await();

}

From source file:com.srotya.sidewinder.core.ingress.binary.NettyBinaryIngestionServer.java

License:Apache License

public void start() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    ServerBootstrap bs = new ServerBootstrap();
    channel = bs.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_RCVBUF, 10485760).option(ChannelOption.SO_SNDBUF, 10485760)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*  w  w w  .j a v  a2  s .c  o  m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new LengthFieldBasedFrameDecoder(3000, 0, 4, 0, 4));
                    p.addLast(new SeriesDataPointDecoder());
                    p.addLast(new SeriesDataPointWriter(storageEngine));
                }

            }).bind("localhost", 9927).sync().channel();
}

From source file:com.srotya.sidewinder.core.ingress.http.NettyHTTPIngestionServer.java

License:Apache License

public void start() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(4);

    ServerBootstrap bs = new ServerBootstrap();
    channel = bs.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_RCVBUF, 10485760).option(ChannelOption.SO_SNDBUF, 10485760)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override//  w ww .jav  a2s .  c  o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpRequestDecoder());
                    p.addLast(new HttpResponseEncoder());
                    p.addLast(new HTTPDataPointDecoder(storageEngine));
                }

            }).bind("localhost", 9928).sync().channel();
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TCPConsumingServer.java

License:Apache License

@Override
protected AbstractBootstrap bootstrap(boolean enableEpoll) {
    if (enableEpoll) {
        enableDirectBuffers();// w  w w  .  j  av a 2 s  .  co m
        // boss group simply opens channels and hands processing off to the child
        EpollEventLoopGroup bossGroup = new EpollEventLoopGroup(NUM_BOSS_THREADS);
        EventLoopGroup workerGroup = new EpollEventLoopGroup(numThreads);
        groups.add(bossGroup);
        groups.add(workerGroup);
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(EpollServerSocketChannel.class)
                .childHandler(this.channelInitializer)
                .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH)
                .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE);
        return b;
    } else {
        disableDirectBuffers();
        EventLoopGroup bossGroup = new NioEventLoopGroup(NUM_BOSS_THREADS);
        EventLoopGroup workerGroup = new NioEventLoopGroup(numThreads);
        groups.add(bossGroup);
        groups.add(workerGroup);
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(this.channelInitializer)
                .option(ChannelOption.SO_BACKLOG, SOCKET_MAX_INBOUND_CONNECTION_QUEUE_DEPTH)
                .childOption(ChannelOption.SO_KEEPALIVE, SOCKET_KEEPALIVE);
        return b;
    }

}

From source file:com.stremebase.examples.todomvc.Todo.java

License:Apache License

public static void main(String[] args) throws Exception {
    css = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "index.css")));
    favicon = Files.readAllBytes(Paths.get(System.getProperty("user.dir"), "Web", "favicon.ico"));

    Table.setDefaultDb(new DB("user.dir"));
    data = new Data(itemTableId, "ITEMTABLE");

    @SuppressWarnings("unchecked")
    Router<Integer> router = new Router<Integer>().GET("/", GET).GET("/filter/:filtertype", FILTER)

            .POST("/", POST).POST("/delete", DELETE).POST("/clearcompleted", DELETECOMPLETED)
            .POST("/toggle-status", TOGGLESTATUS)

            .GET(":something/index.css", CSS).GET("/index.css", CSS).GET("/favicon.ico", ICON)
            .notFound(NOTFOUND);//from w ww.ja v  a  2  s  . c  om
    System.out.println(router);

    OioEventLoopGroup bossGroup = new OioEventLoopGroup(1);
    SingleThreadEventLoop workerGroup = new ThreadPerChannelEventLoop(bossGroup);

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
                .childOption(ChannelOption.SO_REUSEADDR, java.lang.Boolean.TRUE)
                .channel(OioServerSocketChannel.class).childHandler(new HttpRouterServerInitializer(router));

        Channel ch = b.bind(PORT).sync().channel();
        System.out.println("Server started: http://127.0.0.1:" + PORT + '/');

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

From source file:com.study.hc.net.netty.EchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure the server.
    // EventLoopGroup   accept NioEventLoop
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    // EventLoopGroup   I/O
    EventLoopGroup workerGroup2 = new NioEventLoopGroup(1);
    try {// w w w  . jav a2s . c o m
        // ??
        ServerBootstrap b = new ServerBootstrap();
        // ???reactor???
        b.group(bossGroup, workerGroup2).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new EchoServerHandler());
                    }
                });
        // bind??
        ChannelFuture f = b.bind(PORT).sync();
        // ??
        f.channel().closeFuture().sync();
    } finally {
        // 
        bossGroup.shutdownGracefully();
        workerGroup2.shutdownGracefully();
    }
}