Java 类io.netty.channel.nio.NioEventLoopGroup 实例源码

项目:webapp-tyust    文件:NettyServer.java   
private NettyServer(){
    pGroup = new NioEventLoopGroup();
    cGroup = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(pGroup, cGroup)
     .channel(NioServerSocketChannel.class)
     .option(ChannelOption.SO_BACKLOG, 1024)
     //设置日志
     .handler(new LoggingHandler(LogLevel.INFO))
     .childHandler(new ChannelInitializer<SocketChannel>() {
        protected void initChannel(SocketChannel sc) throws Exception {
            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
            sc.pipeline().addLast(new ReadTimeoutHandler(60));
            sc.pipeline().addLast(new NettyServerHandler());
        }
    });     
}
项目:jeesupport    文件:NettyServer.java   
public void start(){
    logger.debug( "--Socket Server will start------------" ) ;
    boss = new NioEventLoopGroup() ;
    work = new NioEventLoopGroup() ;
    int port = CommonConfig.getInteger( SOCKET_PORT1 );
    try {

        logger.info( "Netty Server[" + port + "] started..." ) ;
        ServerBootstrap b = new ServerBootstrap() ;

        b.group( boss , work ) ;
        b.channel( NioServerSocketChannel.class ) ;
        b.childHandler( nettyInitializer ) ;
        b.bind( port ).sync().channel().closeFuture().sync() ;
    } catch ( Exception e ) {
        String err_string = e.toString();
        if( err_string.indexOf( "childHandler" ) != -1 ){
            logger.error( "Netty Server[" + port + "] NettyInitializer can't find." ) ;
        }else{
            logger.error( "Netty Server[" + port + "] onload err:" + e.toString() , e  ) ;
        }
    } finally {
        logger.error( "Netty Server[" + port + "] will be unload..."  ) ;
        unload();
    }
}
项目:JPRE    文件:TestClient.java   
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(this.host, this.port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected server...");
                        ch.pipeline().addLast(new ByteArrayEncoder());
                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        ChannelFuture cf = b.connect().sync();

        cf.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
项目:redant    文件:SlaveServer.java   
public void start(SlaveNode slaveNode) {
    if(slaveNode==null){
        throw new IllegalArgumentException("slaveNode is null");
    }
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 SlaveServerInitializer());

        ChannelFuture future = b.bind(slaveNode.getPort()).sync();
        LOGGER.info("SlaveServer Startup at port:{}",slaveNode.getPort());

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:redant    文件:MasterServer.java   
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 MasterServerInitializer());

        ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
        LOGGER.info("MasterServer Startup at port:{}",CommonConstants.SERVER_PORT);

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        LOGGER.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:redant    文件:NettyServer.java   
public void start() {
    EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
    EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
    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 ServerInitializer());

        ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
        logger.info("NettyServer Startup at port:{}",CommonConstants.SERVER_PORT);

        // 等待服务端Socket关闭
        future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error("InterruptedException:",e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:fresco_floodlight    文件:BootstrapClient.java   
public void init() throws SyncException {
    cg = new DefaultChannelGroup("Cluster Bootstrap", GlobalEventExecutor.INSTANCE);

    workerExecutor = new NioEventLoopGroup();
    timer = new HashedWheelTimer();

    bootstrap = new Bootstrap()
    .group(workerExecutor)
    .channel(NioSocketChannel.class)
    .option(ChannelOption.SO_REUSEADDR, true)
    .option(ChannelOption.SO_KEEPALIVE, true)
    .option(ChannelOption.TCP_NODELAY, true)
    .option(ChannelOption.SO_SNDBUF, RPCService.SEND_BUFFER_SIZE)
    .option(ChannelOption.SO_RCVBUF, RPCService.SEND_BUFFER_SIZE)
    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, RPCService.CONNECT_TIMEOUT);

    pipelineFactory = new BootstrapChannelInitializer(timer, this);
    bootstrap.handler(pipelineFactory);
}
项目:mapsforge-web    文件:HttpServer.java   
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
       EventLoopGroup workerGroup = new NioEventLoopGroup();

       try{
           ServerBootstrap serverBootstrap = new ServerBootstrap();
           serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new HttpServer());
           ChannelFuture channelFuture = serverBootstrap
                .bind(new InetSocketAddress("0.0.0.0", PORT))
                .sync();
           channelFuture.channel().closeFuture().sync();
       } finally {
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
       }
}
项目:monica    文件:SocketClient.java   
public void start(String ip, int port) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new FileClientInitializer(sslCtx));
        Channel ch = b.connect(ip, port).sync().channel();
        ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch);           
    }catch(Exception e){
        e.printStackTrace();
    }
}
项目:ss-java    文件:ShadowsocksClient.java   
public Future startAsync() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new SocksServerInitializer())
             .childAttr(OPTION_ATTRIBUTE_KEY, option);

    return bootstrap.bind(option.getLocalHost(), option.getLocalPort()).addListener(
            new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (infoEnable) {
                        if (future.isSuccess()) {
                            logger.info("Listening on local port {}", option.getLocalPort());
                        } else {
                            logger.info("Shadowsocks client startup failed", future.cause());
                        }
                    }
                }
            });
}
项目:TakinRPC    文件:RemotingNettyClient.java   
private RemotingNettyClient(final NettyClientConfig nettyClientConfig) {
    super(nettyClientConfig.getOnewaySemaphoreValue(), nettyClientConfig.getAsyncSemaphoreValue());
    int publicThreadNums = nettyClientConfig.getCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;
    }
    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    group = new NioEventLoopGroup(nettyClientConfig.getWorkerThreads(), new CustomThreadFactory("client"));

    start();
}
项目:Jenisys3    文件:UDPServerSocket.java   
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
项目:guereza    文件:NettyServer.java   
/**
 * Start the server
 *
 * @param port The port on which the server listen to
 */
public void run(final int port) {
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        final ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ServerInitializer())
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true);

        final ChannelFuture f = bootstrap.bind(port).sync();
        LOGGER.info("NettyServer: running on port {}", port);

        f.channel().closeFuture().sync();
    } catch (final InterruptedException e) {
        LOGGER.error("NettyServer: an error occurred while running: {}", e.getMessage());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
项目:push    文件:Client.java   
public void run() {
    workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        // b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new MsgPackDecode());
                pipeline.addLast("encoder", new MsgPackEncode());
                pipeline.addLast(new ClientHandler());
            }
        });
        channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel();
        status = Status.START;
        channel.closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
    status = Status.STOP;
}
项目:ClusterDeviceControlPlatform    文件:NettyClient.java   
public void start(String hostName, int port) {
    Executors.newSingleThreadExecutor().submit(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new KyChannelInitializer());
        if (hostName != null && !hostName.equals(""))
            bootstrap.remoteAddress(new InetSocketAddress(hostName, port));
        else
            bootstrap.remoteAddress(new InetSocketAddress(port));
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    });
}
项目:io-comparison    文件:NettyClient.java   
@Override
public void connect() throws IOException, InterruptedException {
    workerGroup = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(
                    //new LoggingHandler(LogLevel.INFO),
                    new MsgEncoder(),
                    new MsgDecoder(),
                    new NettyClientHandler()
            );
        }
    });

    ChannelFuture f = b.connect(address, port).sync();
    channel = f.channel();
}
项目:tcp-gateway    文件:TcpClient.java   
/**
 * Init Bootstrap
 */
public static final Bootstrap getBootstrap() {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
            pipeline.addLast("decoder", new ProtobufDecoder(MessageBuf.JMTransfer.getDefaultInstance()));
            pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
            pipeline.addLast("encoder", new ProtobufEncoder());
            pipeline.addLast("handler", new TcpClientHandler());
        }
    });


    b.option(ChannelOption.SO_KEEPALIVE, true);
    return b;
}
项目:ClusterDeviceControlPlatform    文件:NettyServer.java   
public void start() {
    new Thread(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(30232)) //"woodswang",
                .handler(KyChannelInitializer.newInstance());
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    }).start();
}
项目:mini-dubbo    文件:NettyServer.java   
public void doOpen() throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try{
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new ObjectDecoder(1024*1024, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                pipeline.addLast(new ObjectEncoder());
                pipeline.addLast((SimpleChannelInboundHandler)handler);
            }
        });
        serverBootstrap.option(ChannelOption.SO_BACKLOG,1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);
        ChannelFuture future = serverBootstrap.bind(address,port).sync();
        //future.channel().closeFuture().sync();
    }finally{
        //workerGroup.shutdownGracefully();
        //bossGroup.shutdownGracefully();
    }
}
项目:Mods    文件:TF2UdpClient.java   
public TF2UdpClient(InetSocketAddress address) throws Exception {
    group = new NioEventLoopGroup();
    this.address = address;
    EntityPlayerSP player = Minecraft.getMinecraft().player;
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioDatagramChannel.class).handler(new UdpChannelHandlerClient());

    channel = boot.bind(0).sync().channel();

    channel.connect(address);

    /*PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
    buffer.writeShort(playerId);
    buffer.writeShort(0);
    buffer.writeByte(0);
    buffer.writeLong(System.currentTimeMillis());

    channel.writeAndFlush(new DatagramPacket(buffer, address));*/
}
项目:talchain    文件:UdpTest.java   
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
项目:sds    文件:NettyServerServiceImpl.java   
@Override
public synchronized void start() {
    bossGroup = new NioEventLoopGroup(); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SocketServerChannelInitializer(heartTime,socketService,applicationContext));
        // Bind and start to accept incoming connections.
        b.bind(port);

        logger.info("socket: "+port+" starting....");
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:neoscada    文件:Receiver.java   
public Receiver ( final ReceiverHandlerFactory factory, final SocketAddress addr )
{
    this.factory = factory;

    this.bossGroup = new NioEventLoopGroup ();
    this.workerGroup = new NioEventLoopGroup ();
    this.bootstrap = new ServerBootstrap ();
    this.bootstrap.group ( this.bossGroup, this.workerGroup );
    this.bootstrap.channel ( NioServerSocketChannel.class );
    this.bootstrap.option ( ChannelOption.SO_BACKLOG, 5 );
    this.bootstrap.option ( ChannelOption.SO_REUSEADDR, true );
    this.bootstrap.childHandler ( new ChannelInitializer<SocketChannel> () {

        @Override
        protected void initChannel ( final SocketChannel ch ) throws Exception
        {
            handleInitChannel ( ch );
        }
    } );

    this.channel = this.bootstrap.bind ( addr ).channel ();

    logger.info ( "Receiver running ..." );
}
项目:chromium-net-for-android    文件:Http2TestServer.java   
public void run() {
    try {
        // Configure the server.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 1024);
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new Http2ServerInitializer(mSslCtx));

            sServerChannel = b.bind(PORT).sync().channel();
            Log.i(TAG, "Netty HTTP/2 server started on " + getServerUrl());
            sBlock.open();
            sServerChannel.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
        Log.i(TAG, "Stopped Http2TestServerRunnable!");
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
}
项目:nettyRpc    文件:ClientConnectionPool.java   
/**
 * 初始化连接池
 */
public void init() {
    bootstrap = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new LoggingHandler());
    //所有的公用一个eventloopgroup, 对于客户端来说应该问题不大!
    poolMap = new AbstractChannelPoolMap<InetSocketAddress, FixedChannelPool>() {
        @Override
        protected FixedChannelPool newPool(InetSocketAddress key) {
            return new FixedChannelPool(bootstrap.remoteAddress(key), new FixedChannelPoolHandler(), 2);
        }
    };
    //预先建立好链接
    serverListConfig.getAddressList().stream().forEach(address -> {
        poolMap.get(address);
    });
}
项目:iothub    文件:MqttTransportService.java   
@PostConstruct
public void init() throws Exception {
  log.info("Setting resource leak detector level to {}", leakDetectorLevel);
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

  log.info("Starting MQTT transport...");
  log.info("Lookup MQTT transport adaptor {}", adaptorName);
  // this.adaptor = (MqttTransportAdaptor) appContext.getBean(adaptorName);

  log.info("Starting MQTT transport server");
  bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
  workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
  ServerBootstrap b = new ServerBootstrap();
  b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1000).option(ChannelOption.TCP_NODELAY, true)
      .childOption(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
      .childHandler(new MqttTransportServerInitializer(msgProducer, deviceService, authService, assetService,
          assetAuthService, relationService, sslHandlerProvider));

  serverChannel = b.bind(host, port).sync().channel();
  log.info("Mqtt transport started: {}:{}!", host, port);
}
项目:im    文件:EchoServer.java   
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
项目:netty-socks    文件:ServerMain.java   
public void start() throws InterruptedException {
    EventLoopGroup acceptors = new NioEventLoopGroup(socksProperties.getAcceptors());
    EventLoopGroup workers = new NioEventLoopGroup();
    EventLoopGroup forwarders = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(acceptors, workers)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, socksProperties.getBacklog())
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, socksProperties.getConnectTimeoutMillis())
                .childHandler(new Socks5WorkerChannelInitializer(socksProperties, forwarders));

        Address address = socksProperties.getListen();
        ChannelFuture future = bootstrap.bind(address.getHost(), address.getPort()).sync();
        future.channel().closeFuture().sync();
    } finally {
        forwarders.shutdownGracefully();
        workers.shutdownGracefully();
        acceptors.shutdownGracefully();
    }
}
项目:http-proxy-netty    文件:HttpProxyServer.java   
@PostConstruct
public void start() {
    new Thread(() -> {
        logger.info("HttpProxyServer started on port: {}", port);
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(channelInitializer)
                    .bind(port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("shit happens", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }).start();
}
项目:push-server    文件:NettyServerBootstrap.java   
private void bind() throws InterruptedException {
    EventLoopGroup boss = new NioEventLoopGroup(1);
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, worker)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 128)
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childHandler(new NettyServerInitializer());

    ChannelFuture f = bootstrap.bind(port).sync();
    if (f.isSuccess()) {
        logger.info("server start---------------");
    }
}
项目:rskj    文件:UDPServer.java   
public void startUDPServer() throws InterruptedException {
    logger.info("Discovery UDPListener started");
    EventLoopGroup group = new NioEventLoopGroup(1);

    while (!shutdown) {
        Bootstrap bootstrap = this.createBootstrap(group);

        channel = bootstrap.bind(address, port).sync().channel();
        channel.closeFuture().sync();

        logger.warn("UDP channel closed. Recreating after 5 sec pause...");
        TimeUnit.SECONDS.sleep(5);
    }

    group.shutdownGracefully().sync();
}
项目:rskj    文件:JsonRpcNettyServer.java   
public JsonRpcNettyServer(InetAddress host,
                          int port,
                          int socketLinger,
                          boolean reuseAddress,
                          CorsConfiguration corsConfiguration,
                          JsonRpcWeb3FilterHandler jsonRpcWeb3FilterHandler,
                          JsonRpcWeb3ServerHandler jsonRpcWeb3ServerHandler) {
    this.host = host;
    this.port = port;
    this.socketLinger = socketLinger;
    this.reuseAddress = reuseAddress;
    this.corsConfiguration = corsConfiguration;
    this.jsonRpcWeb3FilterHandler = jsonRpcWeb3FilterHandler;
    this.jsonRpcWeb3ServerHandler = jsonRpcWeb3ServerHandler;
    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
}
项目:teslog    文件:HttpHelloWorldServer.java   
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // 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();
    }
}
项目:DNCF    文件:NettyConfiguration.java   
@Bean(name = "workerGroup")
public EventLoopGroup getWorkerGroup() {
    if (isLinux) {
        return new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNCSWorkerThread", Thread.NORM_PRIORITY));
    } else {
        return new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNCSWorkerThread", Thread.NORM_PRIORITY));
    }
}
项目:GitHub    文件:NettyHttpClient.java   
@Override public void prepare(final Benchmark benchmark) {
  this.concurrencyLevel = benchmark.concurrencyLevel;
  this.targetBacklog = benchmark.targetBacklog;

  ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
    @Override public void initChannel(SocketChannel channel) throws Exception {
      ChannelPipeline pipeline = channel.pipeline();

      if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLEngine engine = sslClient.sslContext.createSSLEngine();
        engine.setUseClientMode(true);
        pipeline.addLast("ssl", new SslHandler(engine));
      }

      pipeline.addLast("codec", new HttpClientCodec());
      pipeline.addLast("inflater", new HttpContentDecompressor());
      pipeline.addLast("handler", new HttpChannel(channel));
    }
  };

  bootstrap = new Bootstrap();
  bootstrap.group(new NioEventLoopGroup(concurrencyLevel))
      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
      .channel(NioSocketChannel.class)
      .handler(channelInitializer);
}
项目:hadoop    文件:WebImageViewer.java   
public WebImageViewer(InetSocketAddress address) {
  this.address = address;
  this.bossGroup = new NioEventLoopGroup();
  this.workerGroup = new NioEventLoopGroup();
  this.allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
  this.bootstrap = new ServerBootstrap()
    .group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class);
}
项目:push-network-proxies    文件:NotificationRegisterEndpoint.java   
protected void startNotificationRegisterEndpoint(final String host, final int port) {

        Runnable notificationRegisterEndpointRunnable = new Runnable() {

            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup(1);
                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 NotificationRegisterServerInitializer());

                    Channel ch = b.bind(host, port).sync().channel();

                    logger.info(String.format("Notification register endpoint started at %s:%s", host, port));

                    ch.closeFuture().sync();
                } catch (InterruptedException ex) {
                    logger.info("Notification register endpoint was interrupted.");
                } finally {
                    bossGroup.shutdownGracefully();
                    workerGroup.shutdownGracefully();
                }

            }
        };

        notificationEndpointThread = new Thread(notificationRegisterEndpointRunnable);
        notificationEndpointThread.start();
    }
项目:DNCF    文件:NettyConfiguration.java   
@Bean(name = "workerGroup")
public EventLoopGroup getWorkerGroup() {
    if (isLinux) {
        return new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNWorkerThread", Thread.NORM_PRIORITY));
    } else {
        return new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() + 0x1,
                new NettyThreadFactory("@+DNWorkerThread", Thread.NORM_PRIORITY));
    }
}
项目:BedrockProxy    文件:RakNetServer.java   
/**
 * Constructs a <code>RakNetServer</code> with the specified port, maximum
 * amount connections, maximum transfer unit, and <code>Identifier</code>.
 *
 * @param port                the server port.
 * @param maxConnections      the maximum amount of connections.
 * @param maximumTransferUnit the maximum transfer unit.
 * @param identifier          the <code>Identifier</code>.
 */
public RakNetServer(int port, int maxConnections, int maximumTransferUnit, Identifier identifier) {
    // Set server data
    this.guid = new Random().nextLong();
    this.timestamp = System.currentTimeMillis();
    this.port = port;
    this.maxConnections = maxConnections;
    this.maximumTransferUnit = maximumTransferUnit;
    this.broadcastingEnabled = true;
    this.identifier = identifier;

    // Initiate bootstrap data
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new RakNetServerHandler(this);

    // Set listener
    this.listener = this;

    // Create session map
    this.sessions = new ConcurrentHashMap<InetSocketAddress, RakNetClientSession>();

    // Check maximum transfer unit
    if (this.maximumTransferUnit < RakNet.MINIMUM_TRANSFER_UNIT) {
        throw new IllegalArgumentException(
                "Maximum transfer unit can be no smaller than " + RakNet.MINIMUM_TRANSFER_UNIT);
    }
}
项目:Quavo    文件:NetworkExecutor.java   
/**
 * Starts the network for a {@link Server}.
 * 
 * @param server The {@link Server} to use for building the network.
 * @return <True> If the network started successfully.
 */
public static void start() {
    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();

    bootstrap.group(boss, worker);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            pipeline.addLast("decoder", new ConnectionDecoder());
            pipeline.addLast("encoder", new ConnectionEncoder());
            pipeline.addLast("adapter", new NetworkMessageHandler());
        }

    });
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

    try {
        bootstrap.bind(Constants.HOST_NAME, Constants.HOST_PORT).sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("Server successfully bootstrapped on port " + Constants.HOST_PORT + " and address " + Constants.HOST_NAME + ".");
}