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

下面列出了怎么用io.netty.channel.nio.NioEventLoopGroup的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: mpush   文件: NettyHttpClient.java
@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}
 
源代码2 项目: jdk-source-analysis   文件: TestServer.java
@Test
public void test() throws InterruptedException {
  NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
  NioEventLoopGroup workerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .childHandler(new TestServerInitializer());

    ChannelFuture future = bootstrap.bind(11911).sync();

    future.channel().closeFuture().sync();
  } finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }
}
 
源代码3 项目: JRakNet   文件: DiscoveryThread.java
/**
 * Allocates a discovery thread.
 */
protected DiscoveryThread() {
	this.logger = LogManager.getLogger(DiscoveryThread.class);
	this.bootstrap = new Bootstrap();
	this.group = new NioEventLoopGroup();
	this.handler = new DiscoveryHandler();
	bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
	bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
	try {
		this.channel = bootstrap.bind(0).sync().channel();
	} catch (InterruptedException e) {
		this.interrupt(); // Cause thread to immediately break out of loop
		Discovery.setDiscoveryMode(DiscoveryMode.DISABLED);
		logger.error("Failed to bind channel necessary for broadcasting pings, disabled discovery system");
	}
	this.setName(logger.getName());
}
 
源代码4 项目: archistar-core   文件: ArchistarS3.java
private static Engine createEngine() {
    NioEventLoopGroup loopGroup = new NioEventLoopGroup(16);

    TestServerConfiguration serverConfig = new TestServerConfiguration(createNewServers(), loopGroup);

    serverConfig.setupTestServer(1);
    try {
        CryptoEngine crypto = new RabinBenOrEngine(4, 3, new FakeRandomSource());
        Distributor distributor = new BFTDistributor(serverConfig, loopGroup);
        MetadataService metadata = new SimpleMetadataService(serverConfig, distributor, crypto);
        return new Engine(serverConfig, metadata, distributor, crypto);
    } catch (NoSuchAlgorithmException | WeakSecurityException ex) {
        assert(false);
    }
    return null;
}
 
源代码5 项目: fastdfs-client   文件: FastdfsExecutor.java
FastdfsExecutor(FastdfsSettings settings) {
    loopGroup = new NioEventLoopGroup(settings.maxThreads(), new ThreadFactory() {
        final String threadPrefix = "fastdfs-";
        final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(null, r, threadPrefix + threadNumber.getAndIncrement());
        }
    });
    poolGroup = new FastdfsPoolGroup(
            loopGroup,
            settings.connectTimeout(),
            settings.readTimeout(),
            settings.idleTimeout(),
            settings.maxConnPerHost(),
            settings.maxPendingRequests()
    );
}
 
源代码6 项目: jdk-source-analysis   文件: EchoTest.java
@Test
public void testServer() throws InterruptedException {
  EchoServerHandler serverHandler = new EchoServerHandler();
  EventLoopGroup bossGroup = new NioEventLoopGroup();
  EventLoopGroup wokerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, wokerGroup)
      .channel(NioServerSocketChannel.class)
      .localAddress(new InetSocketAddress(PORT))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addLast(serverHandler);
        }
      });
    ChannelFuture f = b.bind().sync();
    f.channel().closeFuture().sync();
  } finally {
    bossGroup.shutdownGracefully().sync();
    wokerGroup.shutdownGracefully().sync();
  }
}
 
源代码7 项目: iotplatform   文件: 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);
}
 
private Bootstrap initClientBootstrap() {
    Bootstrap b = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    b.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout())
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                clientHandler = new TokenClientHandler(currentState, disconnectCallback);

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
                pipeline.addLast(new NettyResponseDecoder());
                pipeline.addLast(new LengthFieldPrepender(2));
                pipeline.addLast(new NettyRequestEncoder());
                pipeline.addLast(clientHandler);
            }
        });

    return b;
}
 
源代码9 项目: netty4.0.27Learn   文件: SecureChatServer.java
public static void main(String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

    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.INFO))
         .childHandler(new SecureChatServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
 
源代码10 项目: SynapseAPI   文件: SynapseClient.java
public boolean connect() {
    clientGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();  //服务引导程序,服务器端快速启动程序
        b.group(clientGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new SynapseClientInitializer(this));

        b.connect(this.interfaz, this.port).get();
        // 等待服务端监听端口关闭,等待服务端链路关闭之后main函数才退出
        //future.channel().closeFuture().sync();
        return true;
    } catch (Exception e) {
        clientGroup.shutdownGracefully();
        Server.getInstance().getLogger().alert("Synapse Client can't connect to server: " + this.interfaz + ":" + this.port);
        Server.getInstance().getLogger().alert("Reason: " + e.getLocalizedMessage());
        Server.getInstance().getLogger().warning("We will reconnect in 3 seconds");
        this.reconnect();
        return false;
    }
}
 
源代码11 项目: pdown-core   文件: URLHttpDownBootstrapBuilder.java
@Override
public HttpDownBootstrap build() {
  try {
    HttpRequestInfo request = HttpDownUtil.buildRequest(method, url, heads, body);
    request(request);
    if (getLoopGroup() == null) {
      loopGroup(new NioEventLoopGroup(1));
    }
    HttpResponseInfo response = HttpDownUtil.getHttpResponseInfo(request, null, getProxyConfig(), getLoopGroup());
    if (getResponse() == null) {
      response(response);
    } else {
      if (StringUtil.isNullOrEmpty(getResponse().getFileName())) {
        getResponse().setFileName(response.getFileName());
      }
      getResponse().setSupportRange(response.isSupportRange());
      getResponse().setTotalSize(response.getTotalSize());
    }
  } catch (Exception e) {
    if (getLoopGroup() != null) {
      getLoopGroup().shutdownGracefully();
    }
    throw new BootstrapBuildException("build URLHttpDownBootstrap error", e);
  }
  return super.build();
}
 
源代码12 项目: diozero   文件: VoodooSparkProtocolHandler.java
private void connect(String host, int port) throws InterruptedException {
	workerGroup = new NioEventLoopGroup();
	
	ResponseHandler rh = new ResponseHandler(this::messageReceived);
	
	Bootstrap b1 = new Bootstrap();
	b1.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast(new ResponseDecoder(), new MessageEncoder(), rh);
		}
	});
	
	// Connect
	messageChannel = b1.connect(host, port).sync().channel();
}
 
源代码13 项目: deep-spark   文件: ExtractorServer.java
public static void start() throws CertificateException, SSLException, InterruptedException {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

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

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ExtractorServerInitializer(sslCtx));

    b.bind(PORT).sync().channel().closeFuture().sync();
}
 
源代码14 项目: x-pipe   文件: AsyncNettyClientTest.java
protected void doStart() throws Exception {

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1, XpipeThreadFactory.create("NettyKeyedPoolClientFactory"));

        b.group(eventLoopGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new LoggingHandler());
                        p.addLast(new NettySimpleMessageHandler());
                        p.addLast(new NettyClientHandler());
                    }
                });

    }
 
源代码15 项目: elasticsearch-hadoop   文件: BasicSSLServer.java
public void start() throws Exception {
    File cert = Paths.get(getClass().getResource("/ssl/server.pem").toURI()).toFile();
    File keyStore = Paths.get(getClass().getResource("/ssl/server.key").toURI()).toFile();

    SslContext sslCtx = SslContext.newServerContext(cert, keyStore);

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

    server = new ServerBootstrap();
    server.group(bossGroup, workerGroup)
          .channel(NioServerSocketChannel.class)
          .option(ChannelOption.SO_BACKLOG, 100)
          .handler(new LoggingHandler(LogLevel.INFO))
          .childHandler(new BasicSSLServerInitializer(sslCtx));

    server.bind(port).sync().channel().closeFuture();
}
 
源代码16 项目: blog   文件: Server.java
public static void start(final int port) throws Exception {
	EventLoopGroup boss = new NioEventLoopGroup();
	EventLoopGroup woker = new NioEventLoopGroup();
	ServerBootstrap serverBootstrap = new ServerBootstrap();

	try {

		serverBootstrap.channel(NioServerSocketChannel.class).group(boss, woker)
				.childOption(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_BACKLOG, 1024)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast("http-decoder", new HttpServerCodec());
						ch.pipeline().addLast(new HttpServerHandler());
					}
				});

		ChannelFuture future = serverBootstrap.bind(port).sync();
		System.out.println("server start ok port is " + port);
		DataCenter.start();
		future.channel().closeFuture().sync();
	} finally {
		boss.shutdownGracefully();
		woker.shutdownGracefully();
	}
}
 
源代码17 项目: Lottor   文件: EchoClient.java
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group) // 注册线程池
                .channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
                .remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
                .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected...");
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });
        System.out.println("created..");

        ChannelFuture cf = b.connect().sync(); // 异步连接服务器
        System.out.println("connected..."); // 连接完成

        cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
        System.out.println("closed.."); // 关闭完成
    } finally {
        group.shutdownGracefully().sync(); // 释放线程池资源
    }
}
 
源代码18 项目: ndbc   文件: Netty4DataSourceSupplier.java
public Netty4DataSourceSupplier(final Config config,
    final Function<BufferReader, Optional<BufferReader>> transformBufferReader) {
  this.config = config;
  final ChannelSupplier channelSupplier = new ChannelSupplier(
      new NioEventLoopGroup(config.nioThreads().orElse(0), new DefaultThreadFactory("ndbc-netty4", true)),
      config.host(), config.port(), config.charset(), transformBufferReader);
  this.createConnection = createConnectionSupplier(config, channelSupplier);
}
 
源代码19 项目: learning-code   文件: BaseServerTemplate.java
public void serverTask(ChannelHandler... channelHandlers) {
    // bossGroup 用来接收进来的连接
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    // boss 接收的连接注册在 worker 上
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // nio 服务启动辅助类
    ServerBootstrap bootstrap = new ServerBootstrap();
    try {
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // 处理一个已经接收的 channel, 自定义事件处理
                .childHandler(handler())
                // 提供 NioServerSocketChannel 用来接收连接的属性设置
                .option(ChannelOption.SO_BACKLOG, 128)
                // 提供父管道 ServerChannel 接收到连接的属性设置
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口,启动,接收进来的连接
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        // 服务器 socket 关闭
        channelFuture.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        // 优雅退出
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}
 
源代码20 项目: g4proxy   文件: ProxyThreadPools.java
public ProxyThreadPools(SelectorProvider selectorProvider, int incomingAcceptorThreads, int incomingWorkerThreads, int outgoingWorkerThreads, String serverGroupName, int serverGroupId) {
    clientToProxyAcceptorPool = new NioEventLoopGroup(incomingAcceptorThreads, new CategorizedThreadFactory(serverGroupName, "ClientToProxyAcceptor", serverGroupId), selectorProvider);

    clientToProxyWorkerPool = new NioEventLoopGroup(incomingWorkerThreads, new CategorizedThreadFactory(serverGroupName, "ClientToProxyWorker", serverGroupId), selectorProvider);
    clientToProxyWorkerPool.setIoRatio(90);

    proxyToServerWorkerPool = new NioEventLoopGroup(outgoingWorkerThreads, new CategorizedThreadFactory(serverGroupName, "ProxyToServerWorker", serverGroupId), selectorProvider);
    proxyToServerWorkerPool.setIoRatio(90);
}
 
源代码21 项目: dyno   文件: DynoRedissonClient.java
public DynoRedissonClient build() {

            assert (appName != null);
            assert (clusterName != null);
            assert (cpConfig != null);

            DynoCPMonitor cpMonitor = new DynoCPMonitor(appName);
            DynoOPMonitor opMonitor = new DynoOPMonitor(appName);

            RedissonConnectionFactory connFactory = new RedissonConnectionFactory(new NioEventLoopGroup(4), opMonitor);

            ConnectionPoolImpl<RedisAsyncConnection<String, String>> pool = new ConnectionPoolImpl<RedisAsyncConnection<String, String>>(
                    connFactory, cpConfig, cpMonitor, Type.Async);

            try {
                pool.start().get();
            } catch (Exception e) {
                if (cpConfig.getFailOnStartupIfNoHosts()) {
                    throw new RuntimeException(e);
                }

                Logger.warn("UNABLE TO START CONNECTION POOL -- IDLING");
                pool.idle();
            }

            final DynoRedissonClient client = new DynoRedissonClient(appName, pool);
            return client;
        }
 
源代码22 项目: ClusterDeviceControlPlatform   文件: NettyServer.java
@Override
public void start() {
    new Thread(() -> {
        group = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(serverChannelInitializer);
        ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(30232));
        channelFuture.addListener(future -> startListenerHandle(future, launchListener));
    }).start();
}
 
源代码23 项目: neoscada   文件: Server.java
public Server ( final SocketAddress address, final ProtocolOptions options, final List<ServerModule> modules )
{
    this.options = options;

    this.manager = new MessageManager ( this.options );

    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.modules = modules.toArray ( new ServerModule[modules.size ()] );
    for ( final ServerModule module : modules )
    {
        module.initializeServer ( this, this.manager );
    }

    this.channel = this.bootstrap.bind ( address ).channel ();
}
 
源代码24 项目: netty4.0.27Learn   文件: HttpSnoopServer.java
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // Configure the server.
    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.INFO))
         .childHandler(new HttpSnoopServerInitializer(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();
    }
}
 
/** Returns a fixed object pool of handshaker service channel for testing only. */
static FixedObjectPool<ManagedChannel> getHandshakerChannelPoolForTesting(
    String handshakerAddress) {
  ThreadFactory clientThreadFactory = new DefaultThreadFactory("handshaker pool", true);
  ManagedChannel channel =
      NettyChannelBuilder.forTarget(handshakerAddress)
          .directExecutor()
          .eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory))
          .usePlaintext()
          .build();
  return new FixedObjectPool<ManagedChannel>(channel);
}
 
源代码26 项目: glowroot   文件: Http2Server.java
Http2Server(int port, boolean supportHttp1) throws InterruptedException {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(group)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(supportHttp1 ? new Http2ServerWithHttp1SupportInitializer()
                    : new Http2ServerInitializer());
    channel = b.bind(port).sync().channel();
}
 
源代码27 项目: NettyChat   文件: NettyTcpClient.java
/**
 * 初始化bootstrap
 */
private void initBootstrap() {
    EventLoopGroup loopGroup = new NioEventLoopGroup(4);
    bootstrap = new Bootstrap();
    bootstrap.group(loopGroup).channel(NioSocketChannel.class);
    // 设置该选项以后,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    // 设置禁用nagle算法
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    // 设置连接超时时长
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConnectTimeout());
    // 设置初始化Channel
    bootstrap.handler(new TCPChannelInitializerHandler(this));
}
 
源代码28 项目: tajo   文件: HttpFileServer.java
public HttpFileServer(final InetSocketAddress addr) {
  this.addr = addr;
  this.eventloopGroup = new NioEventLoopGroup(2, Executors.defaultThreadFactory());

  // Configure the server.
  this.bootstrap = new ServerBootstrap();
  this.bootstrap.childHandler(new HttpFileServerChannelInitializer())
        .group(eventloopGroup)
        .option(ChannelOption.TCP_NODELAY, true)
        .channel(NioServerSocketChannel.class);
  this.channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
 
源代码29 项目: netty-learning   文件: LineBasedServer.java
public void bind(int port) throws Exception {

		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 ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new LineBasedFrameDecoder(1024));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new LineServerHandler());
				}
			});

			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(port).sync(); // (7)

			logger.info("server bind port:{}", port);

			// Wait until the server socket is closed.
			f.channel().closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
 
源代码30 项目: cim   文件: CIMNioSocketAcceptor.java
private void bindWebPort(){
	webBossGroup = new NioEventLoopGroup();
	webWorkerGroup = new NioEventLoopGroup();
	ServerBootstrap bootstrap = createServerBootstrap(webBossGroup,webWorkerGroup);
	bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

		@Override
		public void initChannel(SocketChannel ch){
			ch.pipeline().addLast(new HttpServerCodec());
			ch.pipeline().addLast(new ChunkedWriteHandler());
			ch.pipeline().addLast(new HttpObjectAggregator(65536));
			ch.pipeline().addLast(new WebMessageEncoder());
			ch.pipeline().addLast(new WebMessageDecoder());
			ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
			ch.pipeline().addLast(channelEventHandler);
		}

	});

	ChannelFuture channelFuture = bootstrap.bind(webPort).syncUninterruptibly();
	channelFuture.channel().newSucceededFuture().addListener(future -> {
		String logBanner = "\n\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"*                   Websocket Server started on port {}.                         *\n" +
				"*                                                                                   *\n" +
				"*                                                                                   *\n" +
				"* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
		LOGGER.info(logBanner, webPort);
	});
	channelFuture.channel().closeFuture().addListener(future -> this.destroy(webBossGroup,webWorkerGroup));
}
 
 类所在包
 同包方法