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.mpush.netty.server.NettyServer.java

License:Apache License

private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work,
        Class<? extends ServerChannel> clazz) {
    /***//from  w ww. j a  v  a 2s. c  o  m
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channel(clazz);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Logs.Console.error("server start success on:{}", port);
                    if (listener != null)
                        listener.onSuccess(port);
                } else {
                    Logs.Console.error("server start failure on:{}", port, future.cause());
                    if (listener != null)
                        listener.onFailure(future.cause());
                }
            }
        });
        if (f.isSuccess()) {
            serverState.set(State.Started);
            /**
             * socket
             */
            f.channel().closeFuture().sync();
        }

    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    } finally {
        /***
         * 
         */
        stop(null);
    }
}

From source file:com.mpush.netty.server.NettyTCPServer.java

License:Apache License

private void createServer(Listener listener, EventLoopGroup boss, EventLoopGroup work,
        ChannelFactory<? extends ServerChannel> channelFactory) {
    /***//from  w  ww  .  j a va  2s  .c o  m
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channelFactory(channelFactory);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<Channel>() { // (4)
            @Override
            public void initChannel(Channel ch) throws Exception {//?
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        b.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                serverState.set(State.Started);
                logger.info("server start success on:{}", port);
                if (listener != null)
                    listener.onSuccess(port);
            } else {
                logger.error("server start failure on:{}", port, future.cause());
                if (listener != null)
                    listener.onFailure(future.cause());
            }
        });
    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    }
}

From source file:com.my.netty.object.ObjectEchoServer.java

License:Apache License

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

        // Bind and start to accept incoming connections.
        System.out.println("server prepare staring");
        b.bind(port).sync().channel().closeFuture().sync();
        System.out.println("server start ok");
    } finally {
        System.out.println("server  do finally");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        System.out.println("server closing ok");
    }
}

From source file:com.mycompany.ffserver.FFServer.java

@Override
public void run() {
    FFDevice ff_device;/*from   www .  j  av  a  2s  . c  om*/
    FFRequest ff_request;
    int dev_count;
    int req_count;

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            device_lst.add(new FFDevice(ch));
            logger.info("have a new connnection");
        }
    });
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        bootstrap.bind(port).sync();
    } catch (InterruptedException ex) {
        logger.error(ex.getMessage());
    }

    ResultSet rs;
    try {
        rs = DbUtils.getDeviceList();
        String reg_str;
        while (rs.next()) {
            reg_str = rs.getString("regs");
            addRegDevice(reg_str);
            DbUtils.updateAllToOffline();
        }
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (SQLException ex) {
        logger.error(ex.getMessage());
    }

    while (!m_stop_flag) {

        dev_count = device_lst.size();

        for (int i = dev_count - 1; i >= 0; i--) {
            ff_device = (FFDevice) device_lst.get(i);

            if (ff_device.isClosed()) {
                device_lst.remove(i);
                logger.info(String.format("remove device with reg_str '%s' from device_lst",
                        ff_device.getRegStr()));
                continue;
            }

            if (ff_device.getRegStr().isEmpty()) {
                if (ff_device.connect_time + 5000 < System.currentTimeMillis()) {
                    ff_device.Close();
                    logger.info("close connection of un-reg device");
                }
                continue;
            }

            if (!dev_info.isAvailable(ff_device.getRegStr())) {
                ff_device.Close();
                logger.info(String.format("close old connection of device that have reg_str '%s'",
                        ff_device.getRegStr()));
                continue;
            }

            dev_info.lockRegStr(ff_device.getRegStr());

            req_count = req_lst.size();
            for (int j = 0; j < req_count; j++) {
                ff_request = req_lst.get(j);
                if (ff_request.reg_str.equals(ff_device.getRegStr()) && ff_device.req == null) {
                    logger.info(String.format("send req to %s", ff_device.getRegStr()));
                    ff_device.req = ff_request;
                    req_lst.remove(j);
                    break;
                }
            }

            ff_device.Process();
        }

        dev_info.freeAllRegStr();

        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            logger.error(ex.getMessage());
        }
    }
}

From source file:com.mycompany.nettyweb.HttpServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w ww . ja v a  2s . co m
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer());

        Channel ch = bootstrap.bind(port).sync().channel();
        System.out.println("Server started, port:" + port);
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.myseti.framework.monitor.net.MonitorServer.java

@Override
public void run() {
    try {//from   w  w w. j a  v a2  s. c o  m
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new MonitorServerHandler()).childHandler(new MonitorServerInitializer(sslCtx));

            b.bind(PORT).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    } catch (Exception ex) {

    }
    super.run(); //To change body of generated methods, choose Tools | Templates.
}

From source file:com.nanxiaoqiang.test.netty.protocol.demo1.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO// w w  w.  j  ava  2  s .c  om
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));// ?
                    ch.pipeline().addLast(new NettyMessageEncoder());// ?
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));// ??
                    ch.pipeline().addLast(new LoginAuthRespHandler());// 
                    ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());// 
                }
            });

    // ???
    ChannelFuture cf = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT);
    cf.channel().closeFuture().sync();
    System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
}

From source file:com.necla.simba.server.gateway.server.frontend.FrontendServer.java

License:Apache License

public FrontendServer(Properties props, BackendConnector backend, StatsCollector stats,
        SubscriptionManager subscriptionManager, ClientAuthenticationManager cam) throws Exception {
    this.backend = backend;

    this.stats = stats;
    assert this.stats != null : "stats must be there already";
    this.subscriptionManager = subscriptionManager;
    this.cam = cam;
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
            .childHandler(new FrontendServerInitializer()).option(ChannelOption.SO_BACKLOG, 128);
    int port = Integer.parseInt(props.getProperty("port", "9000"));
    ChannelFuture f = bootstrap.bind(port).sync();
    f.channel().closeFuture().sync();/*  ww  w  .j a v  a2s.  c om*/
}

From source file:com.net.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO//w ww .  j av  a 2 s. co  m
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws IOException {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                    ch.pipeline().addLast(new ServerHandler(redisTemplate));
                }
            });

    // ???
    b.bind(ContantUtil.port).sync();
    System.out.println("Netty server start ok : " + ("127.0.0.1" + " : " + ContantUtil.port));
}

From source file:com.netflix.hystrix.examples.reactivesocket.HystrixMetricsReactiveSocketServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.out.println("Starting HystrixMetricsReactiveSocketServer...");

    final ReactiveSocketServerHandler handler = ReactiveSocketServerHandler
            .create((setupPayload, rs) -> new EventStreamRequestHandler());

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//w ww  .  ja va2s  . co m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(handler);
                    }
                });
        Channel localhost = b.bind("127.0.0.1", 8025).sync().channel();

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