io.netty.channel.ChannelId Java Examples

The following examples show how to use io.netty.channel.ChannelId. 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: ConnectReceiverTest.java    From lannister with Apache License 2.0 6 votes vote down vote up
private MqttConnAckMessage executeNormalChannelRead0(String clientId, boolean cleanSession, ChannelId channelId)
		throws Exception {
	MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false,
			10);
	MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader("MQTT", 4, true, true, true, 0, true,
			cleanSession, 60);
	MqttConnectPayload payload = new MqttConnectPayload(clientId, "willtopic", "willmessage", "username",
			"password");

	MqttConnectMessage msg = new MqttConnectMessage(fixedHeader, variableHeader, payload);

	ChannelId cid = channelId == null ? TestUtil.newChannelId(clientId, false) : channelId;

	EmbeddedChannel channel = new EmbeddedChannel(cid, new ConnectReceiver());

	channel.writeInbound(msg);

	return channel.readOutbound();
}
 
Example #2
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
private ChannelId[] doTestConnectionIdleTime(ConnectionProvider provider) throws Exception {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .wiretap(true)
			          .handle((req, res) -> res.sendString(Mono.just("hello")))
			          .bindNow();

	Flux<ChannelId> id = createHttpClientForContextWithAddress(provider)
	                       .get()
	                       .uri("/")
	                       .responseConnection((res, conn) -> Mono.just(conn.channel().id())
	                                                              .delayUntil(ch -> conn.inbound().receive()));

	ChannelId id1 = id.blockLast(Duration.ofSeconds(30));
	Thread.sleep(30);
	ChannelId id2 = id.blockLast(Duration.ofSeconds(30));

	assertThat(id1).isNotNull();
	assertThat(id2).isNotNull();

	provider.dispose();
	return new ChannelId[] {id1, id2};
}
 
Example #3
Source File: Sessions.java    From lannister with Apache License 2.0 6 votes vote down vote up
protected void remove(Session session) {
	if (session == null) { return; }

	synchronized (this) {
		try {
			if (session.cleanSession()) { // [MQTT-3.1.2-5]
				sessions.remove(session.clientId());
			}

			ChannelId channelId = session.channelId();
			if (channelId == null) { return; }

			clientIds.remove(channelId);
			ctxs.remove(session.clientId());
		}
		finally {
			if (logger.isDebugEnabled()) {
				logger.debug("session removed [clientId={}, sessionsSize={}, clientIdsSize={}, ctxsSize={}]",
						session.clientId(), sessions.size(), clientIds.size(), ctxs.size());
			}
		}
	}
}
 
Example #4
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
private ChannelId[] doTestConnectionLifeTime(ConnectionProvider provider) throws Exception {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) ->
			              resp.sendObject(ByteBufFlux.fromString(Mono.delay(Duration.ofMillis(30))
			                                                         .map(Objects::toString))))
			          .wiretap(true)
			          .bindNow();

	Flux<ChannelId> id = createHttpClientForContextWithAddress(provider)
	                       .get()
	                       .uri("/")
	                       .responseConnection((res, conn) -> Mono.just(conn.channel().id())
	                                                              .delayUntil(ch -> conn.inbound().receive()));

	ChannelId id1 = id.blockLast(Duration.ofSeconds(30));
	Thread.sleep(10);
	ChannelId id2 = id.blockLast(Duration.ofSeconds(30));

	assertThat(id1).isNotNull();
	assertThat(id2).isNotNull();

	provider.dispose();
	return new ChannelId[] {id1, id2};
}
 
Example #5
Source File: AbstractSessionManager.java    From bitchat with Apache License 2.0 6 votes vote down vote up
@Override
public void removeSession(ChannelId channelId) {
    Assert.notNull(channelId, "channelId can not be null");
    Collection<Session> sessions = allSession();
    if (CollectionUtil.isEmpty(sessions)) {
        return;
    }
    Iterator<Session> iterator = sessions.iterator();
    while (iterator.hasNext()) {
        Session session = iterator.next();
        if (session.channelId() == channelId) {
            iterator.remove();
            log.info("remove a session, session={}, channelId={}", session, channelId);
            break;
        }
    }
}
 
Example #6
Source File: EmbeddedChannelId.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(final ChannelId o) {
    if (o instanceof EmbeddedChannelId) {
        return 0;
    }

    return asLongText().compareTo(o.asLongText());
}
 
Example #7
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionIdleTimeFixedPool() throws Exception {
	ConnectionProvider provider =
			ConnectionProvider.builder("testConnectionIdleTimeFixedPool")
			                  .maxConnections(1)
			                  .pendingAcquireTimeout(Duration.ofMillis(100))
			                  .maxIdleTime(Duration.ofMillis(10))
			                  .build();
	ChannelId[] ids = doTestConnectionIdleTime(provider);
	assertThat(ids[0]).isNotEqualTo(ids[1]);
}
 
Example #8
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionIdleTimeElasticPool() throws Exception {
	ConnectionProvider provider =
			ConnectionProvider.builder("testConnectionIdleTimeElasticPool")
			                  .maxConnections(Integer.MAX_VALUE)
			                  .maxIdleTime(Duration.ofMillis(10))
			                  .build();
	ChannelId[] ids = doTestConnectionIdleTime(provider);
	assertThat(ids[0]).isNotEqualTo(ids[1]);
}
 
Example #9
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 补全 链路信息:根据 channelId 获取 channelInfo 并写入 sn 和 物联网信息
 *
 * @param ctx
 * @param sn
 * @return
 */
public static void setRTUChannelInfo(ChannelHandlerContext ctx, String sn) {
    ChannelId channelId = ctx.channel().id();
    IotInfo iot = GlobalInfo.iotMapper.get(sn);
    GlobalInfo.CHANNEL_INFO_MAP.get(channelId)
            .setSn(sn).setIotInfo(iot).setChannel(ctx.channel());

    RTUChannelInfo channelInfo = GlobalInfo.SN_CHANNEL_INFO_MAP.getOrDefault(sn, RTUChannelInfo.build(sn, channelId));
    channelInfo.setIotInfo(iot).setChannel(ctx.channel());
    GlobalInfo.SN_CHANNEL_INFO_MAP.put(sn, channelInfo);
    LOGGER.info("sn: {} in the house.", sn);
}
 
Example #10
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionNoLifeTimeFixedPool() throws Exception {
	ConnectionProvider provider =
			ConnectionProvider.builder("testConnectionNoLifeTimeFixedPool")
			                  .maxConnections(1)
			                  .pendingAcquireTimeout(Duration.ofMillis(100))
			                  .build();
	ChannelId[] ids = doTestConnectionLifeTime(provider);
	assertThat(ids[0]).isEqualTo(ids[1]);
}
 
Example #11
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("channel out! ----> {}", ctx.channel());
    ChannelId channelId = ctx.channel().id();
    RTUChannelInfo channelInfo = GlobalInfo.CHANNEL_INFO_MAP.remove(channelId);
    GlobalInfo.SN_CHANNEL_INFO_MAP.remove(channelInfo.getSn());
    LOGGER.info("remove channel: {}", channelInfo);
    ctx.fireChannelUnregistered();
}
 
Example #12
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionNoLifeTimeElasticPool() throws Exception {
	ConnectionProvider provider =
			ConnectionProvider.create("testConnectionNoLifeTimeElasticPool", Integer.MAX_VALUE);
	ChannelId[] ids = doTestConnectionLifeTime(provider);
	assertThat(ids[0]).isEqualTo(ids[1]);
}
 
Example #13
Source File: Http2StreamChannelId.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(ChannelId o) {
    if (o instanceof Http2StreamChannelId) {
        Http2StreamChannelId otherId = (Http2StreamChannelId) o;
        int res = parentId.compareTo(otherId.parentId);
        if (res == 0) {
            return id - otherId.id;
        } else {
            return res;
        }
    }
    return parentId.compareTo(o);
}
 
Example #14
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("new channel coming! ----> {}", ctx.channel());
    ChannelId channelId = ctx.channel().id();
    RTUChannelInfo channelInfo = GlobalInfo.CHANNEL_INFO_MAP.getOrDefault(channelId, RTUChannelInfo.build("unknownSN", channelId));
    GlobalInfo.CHANNEL_INFO_MAP.put(channelId, channelInfo);
    ctx.fireChannelRegistered();
}
 
Example #15
Source File: ChannelThreadExecutorGroupTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertUnregister() {
    ChannelId channelId = mock(ChannelId.class);
    ChannelThreadExecutorGroup.getInstance().register(channelId);
    ChannelThreadExecutorGroup.getInstance().unregister(channelId);
    assertNull(ChannelThreadExecutorGroup.getInstance().get(channelId));
}
 
Example #16
Source File: ChannelThreadExecutorGroupTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertRegister() {
    ChannelId channelId = mock(ChannelId.class);
    ChannelThreadExecutorGroup.getInstance().register(channelId);
    assertNotNull(ChannelThreadExecutorGroup.getInstance().get(channelId));
    ChannelThreadExecutorGroup.getInstance().unregister(channelId);
}
 
Example #17
Source File: DefaultChannelGroup.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean add(Channel channel) {
    ConcurrentMap<ChannelId, Channel> map =
        channel instanceof ServerChannel? serverChannels : nonServerChannels;

    boolean added = map.putIfAbsent(channel.id(), channel) == null;
    if (added) {
        channel.closeFuture().addListener(remover);
    }

    if (stayClosed && closed) {

        // First add channel, than check if closed.
        // Seems inefficient at first, but this way a volatile
        // gives us enough synchronization to be thread-safe.
        //
        // If true: Close right away.
        // (Might be closed a second time by ChannelGroup.close(), but this is ok)
        //
        // If false: Channel will definitely be closed by the ChannelGroup.
        // (Because closed=true always happens-before ChannelGroup.close())
        //
        // See https://github.com/netty/netty/issues/4020
        channel.close();
    }

    return added;
}
 
Example #18
Source File: DefaultChannelManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelWrapper getChannelWrapper(ChannelId channelId) {
    Assert.notNull(channelId, "channelId can not be null");
    if (channels.isEmpty()) {
        return null;
    }
    Channel channel = channels.find(channelId);
    return wrapChannel(channel);
}
 
Example #19
Source File: DefaultChannelListener.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void channelInactive(Channel channel) {
    ChannelId channelId = channel.id();
    channelManager.removeChannel(channelId);
    sessionManager.removeSession(channelId);
    SessionHelper.markOffline(channel);
    log.info("Remove an inactive Channel={}", channel);
}
 
Example #20
Source File: Session.java    From lannister with Apache License 2.0 5 votes vote down vote up
@JsonSerialize(using = ChannelIdSerializer.class)
@JsonProperty
public ChannelId channelId() {
	ChannelHandlerContext ctx = NEXUS.channelHandlerContext(clientId);
	if (ctx == null) { return null; }

	return ctx.channel().id();
}
 
Example #21
Source File: SubscriptionManager.java    From esjc with MIT License 5 votes vote down vote up
public void purgeSubscribedAndDropped(ChannelId connectionId) {
    List<SubscriptionItem> subscriptionsToRemove = new ArrayList<>();

    activeSubscriptions.values().stream()
        .filter(s -> s.isSubscribed && s.connectionId.equals(connectionId))
        .forEach(s -> {
            s.operation.connectionClosed();
            subscriptionsToRemove.add(s);
        });

    subscriptionsToRemove.forEach(s -> activeSubscriptions.remove(s.correlationId));
}
 
Example #22
Source File: AbstractSessionManager.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void bound(Session session, ChannelId channelId, long userId) {
    Assert.notNull(session, "session can not be null");
    Assert.notNull(channelId, "channelId can not be null");
    session.bound(channelId, userId);
    sessionMap.putIfAbsent(session.sessionId(), session);
    log.info("bound a new session, session={}, channelId={}", session, channelId);
}
 
Example #23
Source File: DefaultSession.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public void bound(ChannelId channelId, long userId) {
    if (bounded.compareAndSet(false, true)) {
        ChannelWrapper channelWrapper = ChannelHelper.getChannelWrapper(channelId);
        Assert.notNull(channelWrapper, "channelId does not exists");
        this.channelId = channelId;
        this.userId = userId;
        this.channel = channelWrapper.getChannel();
        this.channelType = channelWrapper.getChannelType();
    }
}
 
Example #24
Source File: DefaultSession.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelId channelId() {
    if (!bounded.get()) {
        throw new IllegalStateException("Not bounded yet, Please call bound first");
    }
    return channelId;
}
 
Example #25
Source File: HttpSession.java    From redant with Apache License 2.0 5 votes vote down vote up
public HttpSession(ChannelId id,ChannelHandlerContext context,Long createTime,Long expireTime){
    this.id = id;
    this.context = context;
    this.createTime = createTime;
    this.expireTime = expireTime;
    assertSessionMapNotNull();
}
 
Example #26
Source File: SessionHelper.java    From redant with Apache License 2.0 5 votes vote down vote up
/**
 * 清除过期的session
 * 需要在定时器中执行该方法
 */
public void clearExpireSession(){
    Iterator<Map.Entry<ChannelId,HttpSession>> iterator = manager.sessionMap.entrySet().iterator();
    while(iterator.hasNext()){
        Map.Entry<ChannelId,HttpSession> sessionEntry = iterator.next();
        if(sessionEntry.getValue()==null || sessionEntry.getValue().isExpire()){
            iterator.remove();
        }
    }
}
 
Example #27
Source File: SessionHelper.java    From redant with Apache License 2.0 5 votes vote down vote up
/**
 * 获取单例
 * @return
 */
public static SessionHelper instange(){
    synchronized (SessionHelper.class) {
        if (manager == null) {
            manager = new SessionHelper();
            if (manager.sessionMap == null) {
                // 需要线程安全的Map
                manager.sessionMap = new ConcurrentHashMap<ChannelId,HttpSession>();
            }
        }
    }
    return manager;
}
 
Example #28
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
/**
 * 补全 链路信息:根据 channelId 获取 channelInfo 并写入 sn 和 物联网信息
 *
 * @param ctx
 * @param sn
 * @return
 */
public static void setRTUChannelInfo(ChannelHandlerContext ctx, String sn) {
    ChannelId channelId = ctx.channel().id();
    IotInfo iot = GlobalInfo.iotMapper.get(sn);
    GlobalInfo.CHANNEL_INFO_MAP.get(channelId)
            .setSn(sn).setIotInfo(iot).setChannel(ctx.channel());

    RTUChannelInfo channelInfo = GlobalInfo.SN_CHANNEL_INFO_MAP.getOrDefault(sn, RTUChannelInfo.build(sn, channelId));
    channelInfo.setIotInfo(iot).setChannel(ctx.channel());
    GlobalInfo.SN_CHANNEL_INFO_MAP.put(sn, channelInfo);
    LOGGER.info("sn: {} in the house.", sn);
}
 
Example #29
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("new channel coming! ----> {}", ctx.channel());
    ChannelId channelId = ctx.channel().id();
    RTUChannelInfo channelInfo = GlobalInfo.CHANNEL_INFO_MAP.getOrDefault(channelId, RTUChannelInfo.build("unknownSN", channelId));
    GlobalInfo.CHANNEL_INFO_MAP.put(channelId, channelInfo);
    ctx.fireChannelRegistered();
}
 
Example #30
Source File: ChannelManagerHandler.java    From iot-dc with Apache License 2.0 5 votes vote down vote up
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.info("channel out! ----> {}", ctx.channel());
    ChannelId channelId = ctx.channel().id();
    RTUChannelInfo channelInfo = GlobalInfo.CHANNEL_INFO_MAP.remove(channelId);
    GlobalInfo.SN_CHANNEL_INFO_MAP.remove(channelInfo.getSn());
    LOGGER.info("remove channel: {}", channelInfo);
    ctx.fireChannelUnregistered();
}