当前位置: 首页>>代码示例>>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;未经允许,请勿转载。