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:afred.javademo.proxy.rpc.ObjectEchoServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w  w w.  j  a v  a 2 s  .co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoServerHandler());
                    }
                });

        // Bind and start to accept incoming connections.
        b.bind(8080).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:alluxio.network.protocol.RPCMessageIntegrationTest.java

License:Apache License

@BeforeClass
public static void beforeClass() {
    sEventClient = new NioEventLoopGroup(1);
    sEventServer = new NioEventLoopGroup(1);
    sIncomingHandler = new MessageSavingHandler();

    // Setup the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(sEventServer);//from  w w  w  .ja  v  a2 s .  c om
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new PipelineInitializer(sIncomingHandler));

    InetSocketAddress address = new InetSocketAddress(NetworkAddressUtils.getLocalHostName(100),
            Constants.DEFAULT_MASTER_PORT);
    ChannelFuture cf = bootstrap.bind(address).syncUninterruptibly();
    sLocalAddress = cf.channel().localAddress();

    // Setup the client.
    sBootstrapClient = new Bootstrap();
    sBootstrapClient.group(sEventClient);
    sBootstrapClient.channel(NioSocketChannel.class);
    sBootstrapClient.handler(new PipelineInitializer(new MessageSavingHandler()));
}

From source file:alluxio.worker.netty.NettyDataServer.java

License:Apache License

/**
 * Creates a default {@link io.netty.bootstrap.ServerBootstrap} where the channel and groups are
 * preset./*from  w  ww. j a v  a  2  s  .  c  o m*/
 *
 * @param type the channel type; current channel types supported are nio and epoll
 * @return an instance of {@code ServerBootstrap}
 */
private ServerBootstrap createBootstrapOfType(final ChannelType type) {
    final ServerBootstrap boot = new ServerBootstrap();
    final int bossThreadCount = Configuration.getInt(PropertyKey.WORKER_NETWORK_NETTY_BOSS_THREADS);
    // If number of worker threads is 0, Netty creates (#processors * 2) threads by default.
    final int workerThreadCount = Configuration.getInt(PropertyKey.WORKER_NETWORK_NETTY_WORKER_THREADS);
    final EventLoopGroup bossGroup = NettyUtils.createEventLoop(type, bossThreadCount, "data-server-boss-%d",
            false);
    final EventLoopGroup workerGroup = NettyUtils.createEventLoop(type, workerThreadCount,
            "data-server-worker-%d", false);

    final Class<? extends ServerChannel> socketChannelClass = NettyUtils.getServerChannelClass(type);
    boot.group(bossGroup, workerGroup).channel(socketChannelClass);

    return boot;
}

From source file:app.WebSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w ww. ja v a  2 s .  c om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketServerInitializer());

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

        System.out.println("Listening on ws://0.0.0.0:" + PORT + "/ws");

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

From source file:appium.android.server.http.HttpServer.java

License:Apache License

public void start() {
    if (serverThread != null) {
        throw new IllegalStateException("Server is already running");
    }//from w w w  .j ava  2 s  .  c  o  m
    serverThread = new Thread() {
        @Override
        public void run() {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1);
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
                bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .childHandler(new ServerInitializer(handlers));

                Channel ch = bootstrap.bind(port).sync().channel();
                ch.closeFuture().sync();
            } catch (InterruptedException ignored) {
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                TrafficCounter.shutdown();
            }
        }
    };
    serverThread.start();
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Server listen(SocketAddress inf) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, BACKLOG_VALUE).childOption(ChannelOption.SO_KEEPALIVE, true);

    NettyServer server = new NettyServer(bootstrap, inf);
    server.init();//  ww w .j a va 2s .c om

    return server;
}

From source file:at.yawk.dbus.protocol.DbusConnectorTest.java

@Test(enabled = false)
public void testServer() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.channel(EpollServerDomainSocketChannel.class);
    bootstrap.group(new EpollEventLoopGroup());
    bootstrap.childHandler(new ChannelInitializer<Channel>() {
        @Override//from  ww w .ja va  2s  . c  o m
        protected void initChannel(Channel ch) throws Exception {

            ch.pipeline().addLast(new CommandCodec()).addLast(new ChannelDuplexHandler() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof NegotiateUnixFd) {
                        ch.writeAndFlush(new Error("error"));
                    }

                    if (msg instanceof Begin) {
                        ch.pipeline().addLast(new LoggingInboundAdapter())
                                .addLast(new DbusMainProtocol(new MessageConsumer() {
                                    @Override
                                    public boolean requireAccept(MessageHeader header) {
                                        return true;
                                    }

                                    @Override
                                    public void accept(DbusMessage message) {
                                        DbusMessage response = new DbusMessage();

                                        MessageHeader header = new MessageHeader();
                                        header.setMessageType(MessageType.ERROR);
                                        header.addHeader(HeaderField.REPLY_SERIAL,
                                                BasicObject.createUint32(message.getHeader().getSerial()));
                                        //header.addHeader(HeaderField.SIGNATURE, SignatureObject.create(
                                        //        Collections.singletonList(BasicType.VARIANT)));
                                        header.addHeader(HeaderField.ERROR_NAME,
                                                BasicObject.createString("Error"));
                                        response.setHeader(header);

                                        MessageBody body = new MessageBody();
                                        //body.add(VariantObject.create(BasicObject.createString("testing!")));
                                        response.setBody(body);

                                        ch.writeAndFlush(response);
                                    }
                                }));
                        ch.pipeline().remove((Class) getClass());
                        ch.pipeline().remove(CommandCodec.class);
                    }
                }
            });
            ch.writeAndFlush(new Ok(UUID.randomUUID()));
        }
    });
    bootstrap.bind(new DomainSocketAddress(new File("test")));

    try {
        DbusUtil.callCommand(("dbus-send --address=unix:path=" + new File(".").getAbsolutePath()
                + "/test --dest=org.freedesktop.UPower --print-reply "
                + "/org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.DBus.Properties.Get string:org"
                + ".freedesktop.UPower.Device string:State").split(" "));
    } catch (Exception e) {
        e.printStackTrace();
    }
    TimeUnit.DAYS.sleep(1);
}

From source file:at.yawk.votifier.VotifierServerImpl.java

License:Mozilla Public License

public VotifierServerImpl(Logger logger, VotifierVersion version, SocketAddress listenAddress, PrivateKey key,
        Consumer<VoteEvent> listener) {
    this.logger = logger;
    this.version = version;
    this.listenAddress = listenAddress;
    this.key = key;
    this.listener = listener;

    bootstrap = new ServerBootstrap();
}

From source file:baseFrame.netty.atest.HttpHelloWorldServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from  ww  w .j a v  a  2  s  . c  o  m*/
        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());

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

        System.err.println("Open your web browser and navigate to " + ("http") + "://127.0.0.1:" + PORT + '/');

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

From source file:basic.TimeServer.java

License:Apache License

public void bind(int port) throws Exception {
    // ??NIO//from  www.  j a  v a  2 s.  co 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, 1024).childHandler(new ChildChannelHandler());
        // ???
        ChannelFuture f = b.bind(port).sync();

        // ???
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}