io.netty.channel.group.DefaultChannelGroup Java Examples

The following examples show how to use io.netty.channel.group.DefaultChannelGroup. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BoundNode.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<NodeConnectionReport> closeConnectionAsync(
    SocketAddress connection, CloseType type) {
  Optional<Channel> channel =
      this.clientChannelGroup
          .stream()
          .filter(c -> c.remoteAddress().equals(connection))
          .findFirst();

  if (channel.isPresent()) {
    ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    channelGroup.add(channel.get());
    ClusterConnectionReport clusterReport = new ClusterConnectionReport(getCluster().getId());
    NodeConnectionReport report =
        clusterReport.addNode(this, Collections.singletonList(connection), getAddress());

    return closeChannelGroup(channelGroup, type).thenApply(f -> report);
  } else {
    CompletableFuture<NodeConnectionReport> failedFuture = new CompletableFuture<>();
    failedFuture.completeExceptionally(new IllegalArgumentException("Not found"));
    return failedFuture;
  }
}
 
Example #2
Source File: CatNettyClient.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("cat stopping netty client");

            timer.cancel();
            timer = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            for (Object ch : conns.values()) {
                if (ch != null && ch != dummyChannel)
                    allChannels.add((Channel) ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("cat netty client stopped");
        }
    }
 
Example #3
Source File: NettyServer.java    From Kepler with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NettyServer(String ip, int port) {
    this.ip = ip;
    this.port = port;
    this.channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.bootstrap = new ServerBootstrap();
    this.connectionIds = new AtomicInteger(0);
    this.connectionVersionRuleMap = new HashMap<>();

    for (int i = 0; i < 30; i++) {
        String key = "v" + i + ".version.port";

        if (ServerConfiguration.exists(key)) {
            int portNumber = ServerConfiguration.getInteger(key);

            if (portNumber > 0) {
                this.connectionVersionRuleMap.put(portNumber, new ConnectionVersionRule(portNumber, i));
            }
        }
    }
}
 
Example #4
Source File: NettyHttpServer.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("stopping netty server");

            bossGroup.shutdownGracefully();
            bossGroup = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            allChannels.add(serverChannel);
            for (Channel ch : conns.values()) {
                allChannels.add(ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("netty server stopped");
        }
    }
 
Example #5
Source File: NettyClient.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("stopping netty client");

            timer.stop();
            timer = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            for (Object ch : conns.values()) {
                if (ch != null && ch != dummyChannel)
                    allChannels.add((Channel) ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("netty client stopped");
        }
    }
 
Example #6
Source File: ReplicatorService.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
/**
 * ReplicatorService creates and starts fibers; it must be stopped (or failed) in
 * order to dispose them.
 */
public ReplicatorService(EventLoopGroup bossGroup,
                         EventLoopGroup workerGroup,
                         long nodeId,
                         int port,
                         ModuleInformationProvider moduleInformationProvider,
                         FiberSupplier fiberSupplier,
                         QuorumFileReaderWriter quorumFileReaderWriter) {
  this.bossGroup = bossGroup;
  this.workerGroup = workerGroup;
  this.nodeId = nodeId;
  this.port = port;
  this.moduleInformationProvider = moduleInformationProvider;
  this.fiberSupplier = fiberSupplier;

  this.allChannels = new DefaultChannelGroup(workerGroup.next());
  this.persister = new Persister(quorumFileReaderWriter);
}
 
Example #7
Source File: NettyIoAcceptor.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
public NettyIoAcceptor(NettyIoServiceFactory factory, IoHandler handler) {
    this.factory = factory;
    this.handler = handler;
    channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);;
    bootstrap.group(factory.eventLoopGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, 100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
                }
            });
}
 
Example #8
Source File: NettyIoAcceptor.java    From termd with Apache License 2.0 6 votes vote down vote up
public NettyIoAcceptor(NettyIoServiceFactory factory, final IoHandler handler) {
  this.factory = factory;
  this.handler = handler;
  channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);
  bootstrap.group(factory.eventLoopGroup)
      .channel(NioServerSocketChannel.class)
      .option(ChannelOption.SO_BACKLOG, 100)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline p = ch.pipeline();
          p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
        }
      });
}
 
Example #9
Source File: NettyIoAcceptor.java    From termd with Apache License 2.0 6 votes vote down vote up
public NettyIoAcceptor(NettyIoServiceFactory factory, IoHandler handler) {
  this.factory = factory;
  this.handler = handler;
  channelGroup = new DefaultChannelGroup("sshd-acceptor-channels", GlobalEventExecutor.INSTANCE);;
  bootstrap.group(factory.eventLoopGroup)
      .channel(NioServerSocketChannel.class)
      .option(ChannelOption.SO_BACKLOG, 100)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
          ChannelPipeline p = ch.pipeline();
          p.addLast(new NettyIoSession(NettyIoAcceptor.this, handler).adapter);
        }
      });
}
 
Example #10
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTcpConfiguration_2() throws Exception {
	CountDownLatch latch = new CountDownLatch(10);
	LoopResources loop = LoopResources.create("testTcpConfiguration");
	ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	doTestTcpConfiguration(
			HttpServer.from(configureTcpServer(TcpServer.create(), loop, group, latch)),
			HttpClient.from(configureTcpClient(TcpClient.create(), loop, group, latch))
	);

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	FutureMono.from(group.close())
	          .then(loop.disposeLater())
	          .block(Duration.ofSeconds(30));
}
 
Example #11
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
public void testTcpConfiguration_1() throws Exception {
	CountDownLatch latch = new CountDownLatch(10);
	LoopResources loop = LoopResources.create("testTcpConfiguration");
	ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	doTestTcpConfiguration(
			HttpServer.create().tcpConfiguration(tcp -> configureTcpServer(tcp, loop, group, latch)),
			HttpClient.create().tcpConfiguration(tcp -> configureTcpClient(tcp, loop, group, latch))
	);

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();

	FutureMono.from(group.close())
	          .then(loop.disposeLater())
	          .block(Duration.ofSeconds(30));
}
 
Example #12
Source File: NettyServer.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("stopping netty server");

            bossGroup.shutdownGracefully();
            bossGroup = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            allChannels.add(serverChannel);
            for (Channel ch : conns.values()) {
                allChannels.add(ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("netty server stopped");
        }
    }
 
Example #13
Source File: BaseServerStartup.java    From zuul with Apache License 2.0 6 votes vote down vote up
@Inject
public void init() throws Exception
{
    ChannelGroup clientChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    clientConnectionsShutdown = new ClientConnectionsShutdown(clientChannels,
            GlobalEventExecutor.INSTANCE, discoveryClient);

    addrsToChannelInitializers = chooseAddrsAndChannels(clientChannels);

    server = new Server(
            serverStatusManager,
            addrsToChannelInitializers,
            clientConnectionsShutdown,
            eventLoopGroupMetrics,
            new DefaultEventLoopConfig());
}
 
Example #14
Source File: BaseZuulChannelInitializerTest.java    From zuul with Apache License 2.0 6 votes vote down vote up
@Test
public void tcpHandlersAdded() {
    ChannelConfig channelConfig = new ChannelConfig();
    ChannelConfig channelDependencies = new ChannelConfig();
    channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
    channelDependencies.set(
            ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
    channelDependencies.set(
            ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
    ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    BaseZuulChannelInitializer init =
            new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {

        @Override
        protected void initChannel(Channel ch) {}
    };
    EmbeddedChannel channel = new EmbeddedChannel();

    init.addTcpRelatedHandlers(channel.pipeline());

    assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class));
    assertNotNull(channel.pipeline().context(ServerChannelMetrics.class));
    assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class));
    assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
    assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class));
}
 
Example #15
Source File: ProxyConnectorFactory.java    From styx with Apache License 2.0 6 votes vote down vote up
private ProxyConnector(ConnectorConfig config, ProxyConnectorFactory factory) {
    this.config = requireNonNull(config);
    this.responseEnhancer = requireNonNull(factory.responseEnhancer);
    this.serverConfig = requireNonNull(factory.serverConfig);
    this.metrics = requireNonNull(factory.metrics);
    this.httpErrorStatusListener = requireNonNull(factory.errorStatusListener);
    this.channelStatsHandler = new ChannelStatisticsHandler(metrics);
    this.requestStatsCollector = new RequestStatsCollector(metrics.scope("requests"));
    this.excessConnectionRejector = new ExcessConnectionRejector(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), serverConfig.maxConnectionsCount());
    this.unwiseCharEncoder = new ConfigurableUnwiseCharsEncoder(factory.unwiseCharacters);
    if (isHttps()) {
        this.sslContext = Optional.of(newSSLContext((HttpsConnectorConfig) config, metrics));
    } else {
        this.sslContext = Optional.empty();
    }
    this.requestTracker = factory.requestTracking ? CurrentRequestTracker.INSTANCE : RequestTracker.NO_OP;
    this.httpMessageFormatter = factory.httpMessageFormatter;
    this.originsHeader = factory.originsHeader;
}
 
Example #16
Source File: SelfCheckHttpServer.java    From krpc with Apache License 2.0 6 votes vote down vote up
public void close() {

        if (workerGroup != null) {

            log.info("stopping selfcheck server");

            bossGroup.shutdownGracefully();
            bossGroup = null;

            ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
            allChannels.add(serverChannel);
            for (Channel ch : conns.values()) {
                allChannels.add(ch);
            }
            ChannelGroupFuture future = allChannels.close();
            future.awaitUninterruptibly();

            workerGroup.shutdownGracefully();
            workerGroup = null;

            log.info("selfcheck server stopped");
        }
    }
 
Example #17
Source File: BaseArea.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
public BaseArea(String name, BasePosition entrancePosition, IBaseMap map) {
    this.id = hashCode();
    this.name = name;
    this.map = map;
    this.entrancePosition = entrancePosition;
    this.channelGroup = new DefaultChannelGroup(name, GlobalEventExecutor.INSTANCE);
}
 
Example #18
Source File: NioDatagramChannelTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Test try to reproduce issue #1335
 */
@Test
public void testBindMultiple() throws Exception {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        for (int i = 0; i < 100; i++) {
            Bootstrap udpBootstrap = new Bootstrap();
            udpBootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            // Discard
                            ReferenceCountUtil.release(msg);
                        }
                    });
            DatagramChannel datagramChannel = (DatagramChannel) udpBootstrap
                    .bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
            channelGroup.add(datagramChannel);
        }
        Assert.assertEquals(100, channelGroup.size());
    } finally {
        channelGroup.close().sync();
        group.shutdownGracefully().sync();
    }
}
 
Example #19
Source File: BaseZuulChannelInitializerTest.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Test
public void tcpHandlersAdded_withProxyProtocol() {
    ChannelConfig channelConfig = new ChannelConfig();
    channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true);
    ChannelConfig channelDependencies = new ChannelConfig();
    channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
    channelDependencies.set(
            ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
    channelDependencies.set(
            ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
    ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    BaseZuulChannelInitializer init =
            new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {

                @Override
                protected void initChannel(Channel ch) {}
            };
    EmbeddedChannel channel = new EmbeddedChannel();

    init.addTcpRelatedHandlers(channel.pipeline());

    assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class));
    assertNotNull(channel.pipeline().context(ServerChannelMetrics.class));
    assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class));
    assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
    assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class));
}
 
Example #20
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize internal data structures.
 */
public void init() {
    cg = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    if (tlsParams.isTlsEnabled()) {
        initSsl();
    }

}
 
Example #21
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize internal data structures.
 */
public void init() {
    // These data structures are initialized here because other
    // module's startUp() might be called before ours
    this.controllerNodeIPsCache = new HashMap<>();

    this.systemStartTime = System.currentTimeMillis();

    cg = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    if (tlsParams.isTlsEnabled()) {
        initSsl();
    }
}
 
Example #22
Source File: HttpFileServer.java    From tajo with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: ChannelGroupItem.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
public ChannelGroup getGroup() {
    ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    if(!CollectionUtils.isEmpty(items)) {
        items.forEach((itemId, channel) -> channelGroup.add(channel));
    }
    
    return channelGroup;
}
 
Example #24
Source File: BaseArea.java    From JgFramework with Apache License 2.0 5 votes vote down vote up
public BaseArea(int id, String name, BasePosition entrancePosition, IBaseMap map) {
    this.id = id;
    this.name = name;
    this.map = map;
    this.entrancePosition = entrancePosition;
    this.channelGroup = new DefaultChannelGroup(name, GlobalEventExecutor.INSTANCE);
}
 
Example #25
Source File: AbstractServerBuilder.java    From ob1k with Apache License 2.0 5 votes vote down vote up
public final Server build() {
  final ChannelGroup activeChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
  registerAllServices();
  final StaticPathResolver staticResolver = new StaticPathResolver(contextPath, staticFolders, staticMappings, staticResources);

  final NettyServer server = new NettyServer(port, registry, staticResolver,  activeChannels, contextPath,
          appName, acceptKeepAlive, idleTimeoutMs, supportZip, metricFactory, maxContentLength, requestTimeoutMs, corsConfig);
  server.addListeners(listeners);
  return server;
}
 
Example #26
Source File: TrackerService.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
protected void startUp() throws Exception {
  channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
  EventLoopGroup bossGroup = new NioEventLoopGroup(NUM_BOSS_THREADS,
                                                   new ThreadFactoryBuilder()
                                                     .setDaemon(true).setNameFormat("boss-thread").build());
  EventLoopGroup workerGroup = new NioEventLoopGroup(NUM_WORKER_THREADS,
                                                     new ThreadFactoryBuilder()
                                                       .setDaemon(true).setNameFormat("worker-thread#%d").build());

  bootstrap = new ServerBootstrap()
    .group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class)
    .childHandler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        channelGroup.add(ch);
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("codec", new HttpServerCodec());
        pipeline.addLast("compressor", new HttpContentCompressor());
        pipeline.addLast("aggregator", new HttpObjectAggregator(MAX_INPUT_SIZE));
        pipeline.addLast("handler", new ReportHandler());
      }
    });

  Channel serverChannel = bootstrap.bind(new InetSocketAddress(host, 0)).sync().channel();
  channelGroup.add(serverChannel);

  bindAddress = (InetSocketAddress) serverChannel.localAddress();
  url = URI.create(String.format("http://%s:%d", host, bindAddress.getPort())).toURL();

  LOG.info("Tracker service started at {}", url);
}
 
Example #27
Source File: ThreadPerChannelEventLoopGroupTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private static void runTest(ThreadPerChannelEventLoopGroup loopGroup) throws InterruptedException {
    int taskCount = 100;
    EventExecutor testExecutor = new TestEventExecutor();
    ChannelGroup channelGroup = new DefaultChannelGroup(testExecutor);
    while (taskCount-- > 0) {
        Channel channel = new EmbeddedChannel(NOOP_HANDLER);
        loopGroup.register(channel, new DefaultChannelPromise(channel, testExecutor));
        channelGroup.add(channel);
    }
    channelGroup.close().sync();
    loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync();
    assertTrue(loopGroup.isTerminated());
}
 
Example #28
Source File: ReactorNettyTcpClient.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Simple constructor with the host and port to use to connect to.
 * <p>This constructor manages the lifecycle of the {@link TcpClient} and
 * underlying resources such as {@link ConnectionProvider},
 * {@link LoopResources}, and {@link ChannelGroup}.
 * <p>For full control over the initialization and lifecycle of the
 * TcpClient, use {@link #ReactorNettyTcpClient(TcpClient, ReactorNettyCodec)}.
 * @param host the host to connect to
 * @param port the port to connect to
 * @param codec for encoding and decoding the input/output byte streams
 * @see org.springframework.messaging.simp.stomp.StompReactorNettyCodec
 */
public ReactorNettyTcpClient(String host, int port, ReactorNettyCodec<P> codec) {
	Assert.notNull(host, "host is required");
	Assert.notNull(codec, "ReactorNettyCodec is required");

	this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	this.loopResources = LoopResources.create("tcp-client-loop");
	this.poolResources = ConnectionProvider.elastic("tcp-client-pool");
	this.codec = codec;

	this.tcpClient = TcpClient.create(this.poolResources)
			.host(host).port(port)
			.runOn(this.loopResources, false)
			.doOnConnected(conn -> this.channelGroup.add(conn.channel()));
}
 
Example #29
Source File: WebImageViewer.java    From big-c with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #30
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testChannelGroupClosesAllConnections() throws Exception {
	MonoProcessor<Void> serverConnDisposed = MonoProcessor.create();

	ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor());

	CountDownLatch latch = new CountDownLatch(1);

	DisposableServer boundServer =
			TcpServer.create()
			         .port(0)
			         .doOnConnection(c -> {
			             c.onDispose()
			              .subscribe(serverConnDisposed);
			             group.add(c.channel());
			             latch.countDown();
			         })
			         .wiretap(true)
			         .bindNow();

	TcpClient.create()
	         .remoteAddress(boundServer::address)
	         .wiretap(true)
	         .connect()
	         .subscribe();

	assertTrue(latch.await(30, TimeUnit.SECONDS));

	boundServer.disposeNow();

	FutureMono.from(group.close())
	          .block(Duration.ofSeconds(30));

	serverConnDisposed.block(Duration.ofSeconds(5));
}