當前位置: 首頁>>代碼示例>>Java>>正文


Java ChannelGroup類代碼示例

本文整理匯總了Java中io.netty.channel.group.ChannelGroup的典型用法代碼示例。如果您正苦於以下問題:Java ChannelGroup類的具體用法?Java ChannelGroup怎麽用?Java ChannelGroup使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ChannelGroup類屬於io.netty.channel.group包,在下文中一共展示了ChannelGroup類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: closeConnectionAsync

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@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;
  }
}
 
開發者ID:datastax,項目名稱:simulacron,代碼行數:24,代碼來源:BoundNode.java

示例2: WhirlpoolMessageHandler

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
public WhirlpoolMessageHandler(ChannelGroup channels) {
    this.channels = channels;
    ReadIncomingCallable toClientCallable = new ReadIncomingCallable();
    FutureTask<String> toClientPc = new FutureTask<>(toClientCallable);

    ExecutorService toClientExecutor = Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat("to-client-%d")
                    .build()
    );
    toClientExecutor.execute(toClientPc);

    SendCommandsToKafkaCallable toKafkaCallable = new SendCommandsToKafkaCallable();
    FutureTask<String> toKafka = new FutureTask<>(toKafkaCallable);

    ExecutorService toKafkaExecutor = Executors.newSingleThreadExecutor(
            new ThreadFactoryBuilder()
                    .setDaemon(true)
                    .setNameFormat("to-kafka-%d")
                    .build()
    );
    toKafkaExecutor.execute(toKafka);
}
 
開發者ID:jwboardman,項目名稱:whirlpool,代碼行數:25,代碼來源:WhirlpoolMessageHandler.java

示例3: sendReq

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
private void sendReq(String btyimei) {
    Battery battery = batteryService.fetchBtyByIMEI(btyimei);
    if (battery == null) {
        logger.error("電池不存在, " + btyimei);
        return;
    }
    boolean hasConn = false;
    ChannelGroup channelGroup = SamBtyDataHandler.getChannels();
    for (Channel c : channelGroup) {
        String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get();
        logger.info("已經連接的imei:" + imei);
        if (imei != null && imei.equals(battery.getImei())) {
            c.writeAndFlush("tellme" + imei + "\n");
            hasConn = true;
        }

    }
    if (!hasConn) {
        logger.error("未獲取到長連接, " + btyimei);
    }
}
 
開發者ID:booleguo,項目名稱:sam-elle,代碼行數:22,代碼來源:UserBtyInfoController.java

示例4: chat

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@Override
public boolean chat(String deviceImei, String chatType) {
    Battery battery = batteryService.fetchBtyByIMEI(deviceImei);
    if (battery == null) {
        logger.error("數據庫中設備不存在, 設備Imei卡號:{}", deviceImei);
        return false;
    }
    boolean hasConn = false;
    ChannelGroup channelGroup = SamBtyDataHandler.getChannels();
    for (Channel c : channelGroup) {
        String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get();
        logger.info("已經連接設備的imei:{}", imei);
        if (imei != null && imei.equals(battery.getImei())) {
            String msg = chatType + imei + "\n";
            c.writeAndFlush(msg);
            hasConn = true;
        }

    }
    if (!hasConn) {
        logger.error("未獲取到長連接, 設備Imei卡號:{}", deviceImei);
    }

    return hasConn;

}
 
開發者ID:booleguo,項目名稱:sam-elle,代碼行數:27,代碼來源:DeviceChatServiceImpl.java

示例5: initChannel_adds_OpenChannelLimitHandler_after_RequestInfoSetterHandler_and_uses_cached_ChannelGroup

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@Test
public void initChannel_adds_OpenChannelLimitHandler_after_RequestInfoSetterHandler_and_uses_cached_ChannelGroup() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializer(null, 0, 42, false, null, null);

    // when
    hci.initChannel(socketChannelMock);

    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, RequestInfoSetterHandler> requestInfoSetterHandler = findChannelHandler(handlers, RequestInfoSetterHandler.class);
    Pair<Integer, OpenChannelLimitHandler> openChannelLimitHandler = findChannelHandler(handlers, OpenChannelLimitHandler.class);

    assertThat(requestInfoSetterHandler, notNullValue());
    assertThat(openChannelLimitHandler, notNullValue());

    assertThat(openChannelLimitHandler.getLeft(), is(requestInfoSetterHandler.getLeft() + 1));

    // and then
    ChannelGroup expectedChannelGroup = extractField(hci, "openChannelsGroup");
    ChannelGroup actualChannelGroup = (ChannelGroup) Whitebox.getInternalState(openChannelLimitHandler.getRight(), "openChannelsGroup");
    assertThat(actualChannelGroup, is(expectedChannelGroup));
}
 
開發者ID:Nike-Inc,項目名稱:riposte,代碼行數:26,代碼來源:HttpChannelInitializerTest.java

示例6: channelActive

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    ChannelGroup channelGroup = getServerImpl().getChannelGroup();

    ctx.channel().attr(ServerImpl.REQUEST_CONNECTION_ID).set(channel.id().asLongText());

    channelGroup.add(channel);
    super.channelActive(ctx);
}
 
開發者ID:caricah,項目名稱:iotracah,代碼行數:11,代碼來源:ServerHandler.java

示例7: sendToGroup

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
 * Send to group.
 *
 * @param groupName
 *          the group name
 * @param message
 *          the message
 * @param except
 *          the except
 */
public void sendToGroup(String groupName, byte[] message, SystemIdKey... except) {
  ChannelGroup group = getGroup(groupName);

  if (group == null) return;

  group.forEach(c -> {
    try {
      AbstractRegistryKey<?> systemId = getKeyForChannel(c);
      if (!excepted(systemId, except)) send(systemId, message);
    } catch (Exception e) {
      log.error("Unexpected exception sending message to {}", c, e);
    }
  });

}
 
開發者ID:mrstampy,項目名稱:gameboot,代碼行數:26,代碼來源:OtpNettyGroupRegistry.java

示例8: sendToGroup

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
 * Send to group.
 *
 * @param groupName
 *          the group key
 * @param message
 *          the message
 * @param matcher
 *          the matcher
 * @param listeners
 *          the listeners
 */
public void sendToGroup(String groupName, byte[] message, ChannelMatcher matcher,
    ChannelFutureListener... listeners) {
  groupCheck(groupName);
  checkMessage(message);

  if (!groups.containsKey(groupName)) {
    log.warn("No group {} to send message {}", groupName, message);
    return;
  }

  ChannelGroup group = groups.get(groupName);

  ChannelFutureListener[] all = utils.prependArray(f -> log((ChannelGroupFuture) f, groupName), listeners);
  ChannelGroupFuture cf = group.writeAndFlush(message, matcher);
  cf.addListeners(all);
}
 
開發者ID:mrstampy,項目名稱:gameboot,代碼行數:29,代碼來源:NettyConnectionRegistry.java

示例9: NettyServer

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
public NettyServer(final int port, final ServiceRegistry registry,
                   final StaticPathResolver staticResolver,
                   final ChannelGroup activeChannels, final String contextPath, final String applicationName,
                   final boolean acceptKeepAlive, final long idleTimeoutMs, final boolean supportZip, final MetricFactory metricFactory,
                   final int maxContentLength, final long requestTimeoutMs) {
  System.setProperty("com.outbrain.web.context.path", contextPath);
  this.port = port;
  this.staticResolver = staticResolver;
  this.activeChannels = activeChannels;
  this.contextPath = contextPath;
  this.applicationName = applicationName;
  this.marshallerRegistry = registry.getMarshallerRegistry();
  this.dispatcher = new ServiceDispatcher(registry, marshallerRegistry);
  this.nioGroup = new NioEventLoopGroup();
  this.acceptKeepAlive = acceptKeepAlive;
  this.supportZip = supportZip;
  this.metricFactory = metricFactory;
  this.maxContentLength = maxContentLength;
  this.requestTimeoutMs = requestTimeoutMs;
  this.idleTimeoutMs = idleTimeoutMs;
  registry.logRegisteredEndpoints();
}
 
開發者ID:outbrain,項目名稱:ob1k,代碼行數:23,代碼來源:NettyServer.java

示例10: makeMessageInfoToDevice

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
/**
 * 實際發送消息方法
 * 
 * @param pushMessage
 * @param status
 * @param messageInfo
 * @param deviceId
 * @return
 */
private MessagePushedInfo makeMessageInfoToDevice(ChannelGroup mchannels, MessageInfo messageInfo, DeviceInfo deviceInfo) {
	// System.out.println("makeMessageInfoToDevice come in!");
	// 獲取設備消息發送對象
	MessagePushedInfo messagePushedInfo = getMessagePushedInfo(messageInfo, deviceInfo);
	if (messagePushedInfo != null) {
		// 發送消息
		if (deviceInfo != null && deviceInfo.getIsOnline() == DEVICE_ONLINE_YES) {
			// 如果設備在線 則添加發送通道
			ChannelDeviceInfo channelDeviceInfo = this.getChannelDeviceInfoFromCache(deviceInfo.getDeviceId());
			// System.out.println("makeMessageInfoToDevice channelDeviceInfo=" + channelDeviceInfo);
			Channel channel = channelDeviceInfo == null ? null : channelDeviceInfo.getChannel();
			if (channel != null && channel.isWritable()) {
				mchannels.add(channel);
			} else {
				return null;
			}
		}
	}
	return messagePushedInfo;
}
 
開發者ID:maofw,項目名稱:netty_push_server,代碼行數:30,代碼來源:ApplicationContext.java

示例11: testMasterSlaveSentinelConnectionCount

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@Test
public void testMasterSlaveSentinelConnectionCount() throws Exception {

    ChannelGroup channels = (ChannelGroup) ReflectionTestUtils.getField(sentinelClient, "channels");
    int count = channels.size();

    StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(sentinelClient,
            new Utf8StringCodec(), sentinelUri);

    connection.sync().ping();
    connection.setReadFrom(ReadFrom.SLAVE);
    slaveCall(connection);

    assertThat(channels.size()).isEqualTo(count + 2 /* connections */ + 1 /* sentinel connections */);

    connection.close();
}
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:18,代碼來源:MasterSlaveSentinelTest.java

示例12: testMasterSlaveSentinelClosesSentinelConnections

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
@Test
public void testMasterSlaveSentinelClosesSentinelConnections() throws Exception {

    ChannelGroup channels = (ChannelGroup) ReflectionTestUtils.getField(sentinelClient, "channels");
    int count = channels.size();

    StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(sentinelClient,
            new Utf8StringCodec(), sentinelUri);

    connection.sync().ping();
    connection.setReadFrom(ReadFrom.SLAVE);
    slaveCall(connection);
    connection.close();

    assertThat(channels.size()).isEqualTo(count);
}
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:17,代碼來源:MasterSlaveSentinelTest.java

示例13: MetricBatcher

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
public MetricBatcher(final MetricFactory metricFactory, final int batchBufferCapacity, final ChannelGroup activeChannels, final int maxChannelIdleTime) {
  Preconditions.checkArgument(maxChannelIdleTime > 0, "maxChannelIdleTime must be greater than 0");
  this.maxChannelIdleTime = maxChannelIdleTime;
  Preconditions.checkNotNull(metricFactory, "metricFactory may not be null");
  this.batchBufferCapacity = batchBufferCapacity;
  this.activeChannels = Preconditions.checkNotNull(activeChannels, "activeChannels must not be null");
  prepareNewBatch();

  final String component = getClass().getSimpleName();
  connectionCounter = metricFactory.createCounter(component, "connections");
  metricsCounter = metricFactory.createCounter(component, "metricsReceived");
  unexpectedErrorCounter = metricFactory.createCounter(component, "unexpectedErrors");
  ioErrorCounter = metricFactory.createCounter(component, "ioErrors");
  idleChannelsClosed = metricFactory.createCounter(component, "idleChannelsClosed");
  metricSize = metricFactory.createHistogram(component, "metricSize", false);
  try {
    metricFactory.registerGauge(component, "batchSize", new Gauge<Integer>() {
      @Override
      public Integer getValue() {
        return lastBatchSize.get();
      }
    });
  } catch (IllegalArgumentException e) {
    // ignore metric already exists
  }
}
 
開發者ID:outbrain,項目名稱:gruffalo,代碼行數:27,代碼來源:MetricBatcher.java

示例14: closeChannelGroup

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
private static CompletableFuture<Void> closeChannelGroup(
    ChannelGroup channelGroup, CloseType closeType) {
  switch (closeType) {
    case DISCONNECT:
      return completable(channelGroup.disconnect());
    default:
      return CompletableFuture.allOf(
          channelGroup
              .stream()
              .map(
                  c -> {
                    CompletableFuture<Void> f;
                    Function<SocketChannel, ChannelFuture> shutdownMethod =
                        closeType == CloseType.SHUTDOWN_READ
                            ? SocketChannel::shutdownInput
                            : SocketChannel::shutdownOutput;
                    if (c instanceof SocketChannel) {
                      f = completable(shutdownMethod.apply((SocketChannel) c));
                    } else {
                      logger.warn(
                          "Got {} request for non-SocketChannel {}, disconnecting instead.",
                          closeType,
                          c);
                      f = completable(c.disconnect());
                    }
                    return f;
                  })
              .collect(Collectors.toList())
              .toArray(new CompletableFuture[] {}));
  }
}
 
開發者ID:datastax,項目名稱:simulacron,代碼行數:32,代碼來源:BoundNode.java

示例15: RedisChannelInitializer

import io.netty.channel.group.ChannelGroup; //導入依賴的package包/類
public RedisChannelInitializer(Bootstrap bootstrap, RedisClientConfig config, RedisClient redisClient, ChannelGroup channels, Type type) {
    super();
    this.bootstrap = bootstrap;
    this.config = config;
    this.redisClient = redisClient;
    this.channels = channels;
    this.type = type;
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:9,代碼來源:RedisChannelInitializer.java


注:本文中的io.netty.channel.group.ChannelGroup類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。