Java Code Examples for io.netty.channel.group.ChannelGroup#add()

The following examples show how to use io.netty.channel.group.ChannelGroup#add() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: ApplicationContext.java    From netty_push_server with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 实际发送消息方法
 * 
 * @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;
}
 
Example 8
Source File: ThreadPerChannelEventLoopGroupTest.java    From netty-4.1.22 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(new DefaultChannelPromise(channel, testExecutor));
        channelGroup.add(channel);
    }
    channelGroup.close().sync();
    loopGroup.shutdownGracefully(100, 200, TimeUnit.MILLISECONDS).sync();
    assertTrue(loopGroup.isTerminated());
}
 
Example 9
Source File: CreateGroupRequestHandler.java    From netty-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) {
    List<String> userIdList = createGroupRequestPacket.getUserIdList();

    List<String> userNameList = new ArrayList<>();
    // 1. 创建一个 channel 分组
    ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());

    // 2. 筛选出待加入群聊的用户的 channel 和 userName
    for (String userId : userIdList) {
        Channel channel = SessionUtil.getChannel(userId);
        if (channel != null) {
            channelGroup.add(channel);
            userNameList.add(SessionUtil.getSession(channel).getUserName());
        }
    }

    // 3. 创建群聊创建结果的响应
    String groupId = IDUtil.randomId();
    CreateGroupResponsePacket createGroupResponsePacket = new CreateGroupResponsePacket();
    createGroupResponsePacket.setSuccess(true);
    createGroupResponsePacket.setGroupId(groupId);
    createGroupResponsePacket.setUserNameList(userNameList);

    // 4. 给每个客户端发送拉群通知
    channelGroup.writeAndFlush(createGroupResponsePacket);

    System.out.print("群创建成功,id 为 " + createGroupResponsePacket.getGroupId() + ", ");
    System.out.println("群里面有:" + createGroupResponsePacket.getUserNameList());

    // 5. 保存群组相关的信息
    SessionUtil.bindChannelGroup(groupId, channelGroup);
}
 
Example 10
Source File: JoinGroupRequestHandler.java    From netty-learning-example with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket requestPacket) {
    // 1. 获取群对应的 channelGroup,然后将当前用户的 channel 添加进去
    String groupId = requestPacket.getGroupId();
    ChannelGroup channelGroup = SessionUtil.getChannelGroup(groupId);
    channelGroup.add(ctx.channel());

    // 2. 构造加群响应发送给客户端
    JoinGroupResponsePacket responsePacket = new JoinGroupResponsePacket();

    responsePacket.setSuccess(true);
    responsePacket.setGroupId(groupId);
    ctx.writeAndFlush(responsePacket);
}
 
Example 11
Source File: ChannelsHolder.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 将channel添加到GroupChannel中
 * @param groupId
 * @param channel
 */
public static void addChannelToGroup(String groupId, Channel channel) {
    DefaultChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
    ChannelGroup returnChannelGroup = CHANNEL_GROUPS.putIfAbsent(groupId, channelGroup);
    if(returnChannelGroup == null) {
        // 不存在该ChannelGroup,第一次添加。
        channelGroup.add(channel);
        return;
    }
    // ChannelGroup已经存在
    returnChannelGroup.add(channel);
}
 
Example 12
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());
}