Java Code Examples for io.netty.channel.Channel#isActive()

The following examples show how to use io.netty.channel.Channel#isActive() . 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: RemoterHA.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Write to channel.
 *
 * @param channel the channel
 * @param magicBytes the magic bytes
 * @param pathOrCommand the path or command
 * @param attachment the attachment
 */
private void writeToChannel(Channel channel, String[] magicBytes, Object pathOrCommand, Object attachment) throws ConnectException {
	long firstAttempt = System.currentTimeMillis();
	long timeOut = RemotingConstants.TEN * RemotingConstants.THOUSAND;
	while (!channel.isOpen() || !channel.isActive()) {
		if (System.currentTimeMillis() - firstAttempt >= timeOut) {
			try {
				throw new TimeoutException();
			} catch (TimeoutException e) {
				logger.error("Waited for 10 sec for connection reattempt to JumbuneAgent, but failed to connect", e);
			}
			break;
		}
	}
	if (!channel.isActive()) {
		logger.warn("channel #" + channel.hashCode() + " still disconnected, about to write on disconnected Channel");
	}
	if (attachment != null && attachment instanceof CyclicBarrier) {
		channel.attr(RemotingConstants.barrierKey).set((CyclicBarrier)attachment);
	}else if (attachment != null) {
		channel.attr(RemotingConstants.handlerKey).set((ChannelInboundHandler)attachment);
	}
	channel.write(Unpooled.wrappedBuffer(magicBytes[0].getBytes(), magicBytes[1].getBytes(), magicBytes[2].getBytes()));
	channel.write(pathOrCommand);
	channel.flush();
}
 
Example 2
Source File: DefaultSocketStats.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
protected void doTask() {
    Channel channel = session.getChannel();
    if(channel == null || !channel.isActive()) {
        logger.warn("[doTask] Channel null");
        return;
    }
    if(localPort == -1 && remotePort == -1) {
        localPort = ((InetSocketAddress) channel.localAddress()).getPort();
        remotePort = ((InetSocketAddress) channel.remoteAddress()).getPort();
    }

    new SocketStatsScriptExecutor(localPort, remotePort)
            .execute()
            .addListener(future -> result.set(future.getNow()));
}
 
Example 3
Source File: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 6 votes vote down vote up
@Override
public void reqQryAccountRegister(RequestIdentity requestIdentity, FtdcReq accountRegister) {
	ApplicationRuntime.bindRequestIdentiity(requestIdentity);
	Channel ftdcChannel = ApplicationRuntime.getFtdcChannel(requestIdentity.getBrokerId(), requestIdentity.getUserId());
	if(ftdcChannel == null) {
		getRequestSpi(requestIdentity);
		return;
	}
	FtdcTraderSpi ftdcTraderSpi = getSpi(ftdcChannel);
	if(ftdcChannel.isActive()) {
		ByteBuf buffer = ftdcChannel.alloc().buffer();
		accountRegister.write(buffer.retain());
		FtdcProtocol ftdc = new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), requestIdentity.getReqId(), TID.AccountRegisterReq.id(), Sequence.AccountRegister);
		ftdcChannel.writeAndFlush(ftdc);
	}else {
		fireRspError(ftdcTraderSpi, requestIdentity);
	}		
}
 
Example 4
Source File: AbstractPollingSession.java    From socketio with Apache License 2.0 6 votes vote down vote up
@Override
public void disconnect() {
  if (getState() == State.DISCONNECTED) {
    return;
  }
  if (getState() != State.DISCONNECTING) {
    setState(State.DISCONNECTING);

    // Check if there is active polling channel and disconnect
    // otherwise schedule forced disconnect
    Channel channel = outChannelHolder.getAndSet(null);
    if (channel != null && channel.isActive()) {
      disconnect(channel);
    } else {
      heartbeatScheduler.scheduleDisconnect();
    }
  } else {
    //forced disconnect
    disconnect(null);
  }
}
 
Example 5
Source File: TransportBase.java    From krpc with Apache License 2.0 6 votes vote down vote up
public boolean send(String connId, RpcData data) {

        if (data == null)
            return false;

        if (stopFlag.get() && isServerSide() ) { // allow response, disallow request
            if (isRequest(data.getMeta()))
                return false;
        }

        Channel ch = getChannel(connId);
        if (ch == null) {
            log.error("connection not found, connId={}", connId);
            return false;
        }

        if (ch.isActive()) {
            ch.writeAndFlush(data);
            return true;
        }

        return false;
    }
 
Example 6
Source File: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 6 votes vote down vote up
@Override
public void reqQryInstrument(RequestIdentity requestIdentity, FtdcReq info) {
	ApplicationRuntime.bindRequestIdentiity(requestIdentity);
	Channel ftdcChannel = ApplicationRuntime.getFtdcChannel(requestIdentity.getBrokerId(), requestIdentity.getUserId());
	if(ftdcChannel == null) {
		getRequestSpi(requestIdentity);
		return;
	}
	FtdcTraderSpi ftdcTraderSpi = getSpi(ftdcChannel);
	if(ftdcChannel.isActive()) {
		ByteBuf buffer = ftdcChannel.alloc().buffer();
		info.write(buffer.retain());
		FtdcProtocol ftdc = new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), requestIdentity.getReqId(), TID.QryInstrumentReq.id(), Sequence.QryInstrument);
		ftdcChannel.writeAndFlush(ftdc);
	}else {
		fireRspError(ftdcTraderSpi, requestIdentity);
	}	
}
 
Example 7
Source File: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 6 votes vote down vote up
@Override
public void reqQryContractBank(RequestIdentity requestIdentity, FtdcReq contractBank) {
	ApplicationRuntime.bindRequestIdentiity(requestIdentity);
	Channel ftdcChannel = ApplicationRuntime.getFtdcChannel(requestIdentity.getBrokerId(), requestIdentity.getUserId());
	if(ftdcChannel == null) {
		getRequestSpi(requestIdentity);
		return;
	}
	FtdcTraderSpi ftdcTraderSpi = getSpi(ftdcChannel);
	if(ftdcChannel.isActive()) {
		ByteBuf buffer = ftdcChannel.alloc().buffer();
		contractBank.write(buffer.retain());
		FtdcProtocol ftdc = new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), requestIdentity.getReqId(), TID.ContractbankReq.id(), Sequence.ContractBank);
		ftdcChannel.writeAndFlush(ftdc);
	}else {
		fireRspError(ftdcTraderSpi, requestIdentity);
	}		
}
 
Example 8
Source File: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 6 votes vote down vote up
@Override
public void reqOrderInput(RequestIdentity requestIdentity, FtdcReq inputOrder) {
	ApplicationRuntime.bindRequestIdentiity(requestIdentity);
	Channel ftdcChannel = ApplicationRuntime.getFtdcChannel(requestIdentity.getBrokerId(), requestIdentity.getUserId());
	if(ftdcChannel == null) {
		getRequestSpi(requestIdentity);
		logger.info("{} send to ctp with error of ftdc channel is null", requestIdentity);
		return;
	}
	FtdcTraderSpi ftdcTraderSpi = getSpi(ftdcChannel);
	if(ftdcChannel.isActive()) {
		UserSession session = session(ftdcChannel);
		if(session != null) {
			((ReqInputOrder)inputOrder).setOrderRef(String.valueOf(session.orderRef()));
		}
		ByteBuf buffer = ftdcChannel.alloc().buffer();
		inputOrder.write(buffer.retain());
		FtdcProtocol ftdc = new FtdcProtocol(FtdType.FTDTypeCompressed, buffer, FtdcType.REQ.type(), requestIdentity.getReqId(), TID.OrderInsertReq.id(), Sequence.OrderInsert);
		ftdcChannel.writeAndFlush(ftdc);
		logger.info("{} send to ctp", requestIdentity);
	}else {
		fireRspError(ftdcTraderSpi, requestIdentity);
		logger.warn("{} send to ctp with error of channel not active", requestIdentity);
	}		
}
 
Example 9
Source File: ChannelManager.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
public void broadcastMessage(Object msg) {
	System.out.println("broad count:" + clientCount());
	for (Channel ch : channels.values()) {
		if (ch != null && ch.isActive()) {
			ch.writeAndFlush(safeDuplicate(msg));
		}
	}
}
 
Example 10
Source File: TcpChannelMsgManage.java    From jt809-tcp-server with MIT License 5 votes vote down vote up
/**
 * 获取缓存
 * @param tid
 * @return
 */
public Channel getChannel(String tid){
    Channel channel = CHANNEL_MAP.get(tid);
    if(null != channel && channel.isActive()){
        return channel;
    }
    return null;
}
 
Example 11
Source File: HttpRequestOperation.java    From styx with Apache License 2.0 5 votes vote down vote up
public void write() {
    Channel originChannel = this.nettyConnection.channel();
    if (originChannel.isActive()) {
        io.netty.handler.codec.http.HttpRequest httpRequest = makeRequest(request);

        originChannel.writeAndFlush(httpRequest)
            .addListener(subscribeToRequestBody());
    } else {
        responseFromOriginFlux.error(new TransportLostException(originChannel.remoteAddress(), nettyConnection.getOrigin()));
    }
}
 
Example 12
Source File: UserInfoManager.java    From HappyChat with Apache License 2.0 5 votes vote down vote up
/**
 * 扫描并关闭失效的Channel
 */
public static void scanNotActiveChannel() {
    Set<Channel> keySet = userInfos.keySet();
    for (Channel ch : keySet) {
        UserInfo userInfo = userInfos.get(ch);
        if (userInfo == null) continue;
        if (!ch.isOpen() || !ch.isActive() || (!userInfo.isAuth() &&
                (System.currentTimeMillis() - userInfo.getTime()) > 10000)) {
            removeChannel(ch);
        }
    }
}
 
Example 13
Source File: MP4Handler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private void doFlush(boolean allowWaiting) throws IOException {
   Channel ch = ctx.channel();
   if (ch == null || !ch.isActive()) {
      throw new ClosedChannelException();
   }

   if (allowWaiting) {
      blockUntilReady();
   }

   ctx.writeAndFlush(new DefaultHttpContent(buf.copy()));
   buf.clear();
}
 
Example 14
Source File: UserInfoManager.java    From netty-chat with Apache License 2.0 5 votes vote down vote up
public static boolean saveUser(Channel channel, String nick, String password) {
    UserInfo userInfo = userInfos.get(channel);
    if (userInfo == null) {
        return false;
    }
    if (!channel.isActive()) {
        logger.error("channel is not active, address: {}, nick: {}", userInfo.getAddr(), nick);
        return false;
    }
    // 验证用户名和密码
    if (nick == null || password == null) {
        return false;
    }
    LambdaQueryWrapper<Account> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.eq(Account::getUsername, nick).eq(Account::getPassword, password);
    Account account = accountMapperStatic.selectOne(lambdaQueryWrapper);
    if (account == null) {
        return false;
    }
    // 增加一个认证用户
    userCount.incrementAndGet();
    userInfo.setNick(nick);
    userInfo.setAuth(true);
    userInfo.setId(account.getId());
    userInfo.setUsername(account.getUsername());
    userInfo.setGroupNumber(account.getGroupNumber());
    userInfo.setTime(System.currentTimeMillis());

    // 注册该用户推送消息的通道
    offlineInfoTransmitStatic.registerPull(channel);
    return true;
}
 
Example 15
Source File: HttpNoticeChannelHandler.java    From proxy with MIT License 5 votes vote down vote up
/**
 * 关闭用户连接
 */
private void closeChannle(ChannelHandlerContext ctx) {

    Channel channel = ctx.channel();
    if (channel != null && channel.isActive()) {
        channel.close();
    }
}
 
Example 16
Source File: TcpRepository.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
/**
 * 服务器优雅关闭时,关闭所有的已激活 Channel
 */
public void removeAllChannel() {
    for (int i = 1; i < CHANNEL_ARRAY.length(); i++) {
        Channel channel = CHANNEL_ARRAY.get(i);
        if (channel != null && channel.isActive()) {
            channel.disconnect();
        }
    }
}
 
Example 17
Source File: RemoterNonHA.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
	 * Write to channel.
	 *
	 * @param channel the channel
	 * @param magicBytes the magic bytes
	 * @param pathOrCommand the path or command
	 * @param attachment the attachment
	 */
	private void writeToChannel(Channel channel, String[] magicBytes, Object pathOrCommand, Object attachment) throws ConnectException {

		//update leader agent details
//		if (pathOrCommand instanceof CommandWritable
//				&& ((CommandWritable) pathOrCommand).isCommandForMaster()) {
//			CommandWritable commandWritable = (CommandWritable) pathOrCommand;
//			AgentNode agent = ZKUtils.getLeaderAgentfromZK();
//			commandWritable.setNameNodeHost(agent.getHost());
//			if(commandWritable.isHasSshAuthKeysFile()){
//				commandWritable.setSshAuthKeysFile(agent.getPrivateKey());
//			}
//		}

		long firstAttempt = System.currentTimeMillis();
		long timeOut = RemotingConstants.TEN * RemotingConstants.THOUSAND;
		while (!channel.isOpen() || !channel.isActive()) {
			if (System.currentTimeMillis() - firstAttempt >= timeOut) {
				try {
					throw new TimeoutException();
				} catch (TimeoutException e) {
					logger.error("Waited for 10 sec for connection reattempt to JumbuneAgent, but failed to connect", e);
				}
				break;
			}
		}
		if (!channel.isActive()) {
			logger.warn("channel #" + channel.hashCode() + " still disconnected, about to write on disconnected Channel");
		}
		if (attachment != null && attachment instanceof CyclicBarrier) {
			channel.attr(RemotingConstants.barrierKey).set((CyclicBarrier)attachment);
		}else if (attachment != null) {
			channel.attr(RemotingConstants.handlerKey).set((ChannelInboundHandler)attachment);
		}
		channel.write(Unpooled.wrappedBuffer(magicBytes[0].getBytes(), magicBytes[1].getBytes(), magicBytes[2].getBytes()));
		channel.write(pathOrCommand);
		channel.flush();
	}
 
Example 18
Source File: SocksServerUtils.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Closes the specified channel after all queued write requests are flushed.
 */
public static void closeOnFlush(Channel ch) {
    if (ch.isActive()) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 19
Source File: NettyUtils.java    From multi-model-server with Apache License 2.0 4 votes vote down vote up
/** Closes the specified channel after all queued write requests are flushed. */
public static void closeOnFlush(Channel ch) {
    if (ch.isActive()) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 20
Source File: CleanUpUtil.java    From codes-scratch-zookeeper-netty with Apache License 2.0 4 votes vote down vote up
public static void closeOnFlush(Channel ch) {
    if (ch.isActive()) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}