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

The following are Jave code examples for showing how to use isActive() of the io.netty.channel.Channel class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: AgentX   File: XChannelMapper.java   Source Code and License Vote up 6 votes
static void closeChannelGracefully(InetSocketAddress udpSource) {
    Channel socksChannel = removeSocksMapping(udpSource);
    Channel udpChannel = removeUdpMapping(udpSource);
    Channel tcpChannel = removeTcpMapping(udpSource);
    if (tcpChannel.isActive()) {
        tcpChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        log.info("\t          Proxy << Target \tDisconnect");
    }
    if (socksChannel.isActive()) {
        socksChannel.close();
        log.info("\tClient << Proxy           \tDisconnect");
    }
    if (udpChannel.isActive()) {
        udpChannel.close();
    }
}
 
Example 2
Project: TakinRPC   File: RemotingNettyClient.java   Source Code and License Vote up 6 votes
/**
 * 发起同步调用
 * 其实后面也是异步的
 * 这个同步是指:可以携带结果返回
 * 
 * @param address
 * @param message
 * @param timeout
 * @return 
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public RemotingProtocol invokeSync(String address, final RemotingProtocol message, int timeout) throws Exception, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
    final Channel channel = this.createChannel(address);
    if (channel != null && channel.isActive()) {
        try {
            RemotingProtocol proto = invokeSyncImpl(channel, message, timeout);
            //                logger.info(String.format("%s", Thread.currentThread().getName()));
            //                logger.info(String.format("invokesync use:%s", watch.toString()));
            return proto;
        } catch (Exception e) {
            logger.error("", e);
            throw e;
        }
    } else {
        closeChannel(channel, address);
        throw new RemotingConnectException(address);
    }
}
 
Example 3
Project: wechat-mall   File: NettyRemotingClient.java   Source Code and License Vote up 6 votes
@Override
public void invokeAsync(String addr, RemotingCommand request, long timeoutMillis,
        InvokeCallback invokeCallback) throws InterruptedException, RemotingConnectException,
        RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException {
    final Channel channel = this.getAndCreateChannel(addr);
    if (channel != null && channel.isActive()) {
        if (this.rpcHook != null) {
            this.rpcHook.doBeforeRequest(addr, request);
        }
        this.invokeAsyncImpl(channel, request, timeoutMillis, invokeCallback);
    }
    else {
        this.closeChannel(addr, channel);
        throw new RemotingConnectException(addr);
    }
}
 
Example 4
Project: wechat-mall   File: NettyRemotingClient.java   Source Code and License Vote up 6 votes
@Override
public void invokeOneway(String addr, RemotingCommand request, long timeoutMillis)
        throws InterruptedException, RemotingConnectException, RemotingTooMuchRequestException,
        RemotingTimeoutException, RemotingSendRequestException {
    final Channel channel = this.getAndCreateChannel(addr);
    if (channel != null && channel.isActive()) {
        try {
            if (this.rpcHook != null) {
                this.rpcHook.doBeforeRequest(addr, request);
            }
            this.invokeOnewayImpl(channel, request, timeoutMillis);
        }
        catch (RemotingSendRequestException e) {
            log.warn("invokeOneway: send request exception, so close the channel[{}]", addr);
            this.closeChannel(addr, channel);
            throw e;
        }
    }
    else {
        this.closeChannel(addr, channel);
        throw new RemotingConnectException(addr);
    }
}
 
Example 5
Project: ss-java   File: ChannelUtils.java   Source Code and License Vote up 5 votes
/**
 * 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 6
Project: HappyChat   File: UserInfoManager.java   Source Code and License Vote up 5 votes
public static void addChannel(Channel channel) {
    String remoteAddr = NettyUtil.parseChannelRemoteAddr(channel);
    if (!channel.isActive()) {
        logger.error("channel is not active, address: {}", remoteAddr);
    }
    UserInfo userInfo = new UserInfo();
    userInfo.setAddr(remoteAddr);
    userInfo.setChannel(channel);
    userInfo.setTime(System.currentTimeMillis());
    userInfos.put(channel, userInfo);
}
 
Example 7
Project: AgentX   File: Udp2TcpHandler.java   Source Code and License Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    DatagramPacket datagram = (DatagramPacket) msg;
    InetSocketAddress sender = datagram.sender();
    Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
    if (tcpChannel == null) {
        // udpSource not registered, actively discard this packet
        // without register, an udp channel cannot relate to any tcp channel, so remove the map
        XChannelMapper.removeUdpMapping(sender);
        log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
    } else if (tcpChannel.isActive()) {
        ByteBuf byteBuf = datagram.content();
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                log.info("\t          Proxy << Target \tFrom   {}:{}", sender.getHostString(), sender.getPort());

                // write udp payload via tcp channel
                tcpChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes))));
                log.info("\tClient << Proxy           \tGet [{} bytes]", bytes.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 8
Project: AgentX   File: XChannelMapper.java   Source Code and License Vote up 5 votes
static void closeChannelGracefully(InetSocketAddress udpSource) {
    Channel udpChannel = removeUdpMapping(udpSource);
    Channel tcpChannel = removeTcpMapping(udpSource);
    if (udpChannel.isActive()) {
        log.info("\t          Proxy << Target \tDisconnect");
        udpChannel.close();
    }
    if (tcpChannel.isActive()) {
        tcpChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        log.info("\tClient << Proxy           \tDisconnect");
    }
}
 
Example 9
Project: TakinRPC   File: RemotingNettyClient.java   Source Code and License Vote up 5 votes
@SuppressWarnings("rawtypes")
public void invokeASync(String address, final RemotingProtocol message, int timeout, InvokeCallback callback) throws Exception, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException {
    final Channel channel = this.createChannel(address);
    if (channel != null && channel.isActive()) {
        try {
            invokeAsyncImpl(channel, message, timeout, callback);
        } catch (Exception e) {
            logger.error("", e);
            throw e;
        }
    } else {
        closeChannel(channel, address);
        throw new RemotingConnectException(address);
    }
}
 
Example 10
Project: JavaQuarkBBS   File: ChannelManager.java   Source Code and License Vote up 5 votes
/**
 * 添加Channel
 * @param channel
 */
public void addChannel(Channel channel){
    String remoteAddr = NettyUtil.parseChannelRemoteAddr(channel);
    if (!channel.isActive())  logger.error("channel is not active, address: {}", remoteAddr);
    ChatUser chatUser = new ChatUser();
    chatUser.setAddr(remoteAddr);
    chatUser.setChannel(channel);
    chatUserMap.put(channel,chatUser);
}
 
Example 11
Project: JavaQuarkBBS   File: ChannelManager.java   Source Code and License Vote up 5 votes
/**
 * 扫描并关闭失效的Channel
 */
public void scanNotActiveChannel(){
    Set<Channel> keySet = chatUserMap.keySet();
    for (Channel ch : keySet) {
        ChatUser cUser = chatUserMap.get(ch);
        if (cUser==null) continue;
        if (!ch.isOpen() || !ch.isActive() || (!cUser.isAuth() &&
                (System.currentTimeMillis() - cUser.getTime()) > 10000))
            removeChannel(ch);
    }
}
 
Example 12
Project: netty-connection-pool   File: BasicMultiNodeConnPool.java   Source Code and License Vote up 5 votes
@Override
public final void release(final List<Channel> conns) {
	String nodeAddr;
	Queue<Channel> connQueue;
	for(final Channel conn : conns) {
		nodeAddr = conn.attr(ATTR_KEY_NODE).get();
		if(conn.isActive()) {
			connQueue = availableConns.get(nodeAddr);
			connQueue.add(conn);
			concurrencyThrottle.release();
		} else {
			conn.close();
		}
	}
}
 
Example 13
Project: kcp-netty   File: Utils.java   Source Code and License Vote up 5 votes
static void fireExceptionAndClose(Channel channel, Throwable t, boolean close) {
    channel.pipeline().fireExceptionCaught(t);
    if (channel.isActive()) {
        Channel.Unsafe unsafe = channel.unsafe();
        unsafe.close(unsafe.voidPromise());
    }
}
 
Example 14
Project: elephant   File: TransactionCheckJob.java   Source Code and License Vote up 5 votes
private void sentToClient(RemotingCommand request){
	Map<String,Set<Channel>> groupChannelTable = this.producerManager.getGroupChannelTable();
	if(groupChannelTable.get(request.getGroup()) == null || 
			CollectionUtils.isEmpty(groupChannelTable.get(request.getGroup()))){
		return;
	}
	List<Channel> channels = Lists.newArrayList(groupChannelTable.get(request.getGroup()));
	Channel c = channels.get(new Random().nextInt(channels.size()));
	if(c.isActive()){
		c.writeAndFlush(request);
	}
}
 
Example 15
Project: ClusterDeviceControlPlatform   File: TcpRepository.java   Source Code and License Vote up 5 votes
/**
 * 手动移除相应的 Channel
 *
 * @param channel 欲被手动移除的 Channel
 */
private void manualRemoveChannel(Channel channel) {
    if (channel.isActive()) {
        channel.disconnect();
    } else {
        removeChannelCompleted(channel);
    }
}
 
Example 16
Project: HappyChat   File: UserInfoManager.java   Source Code and License Vote up 5 votes
/**
 * 扫描并关闭失效的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 17
Project: DistributedID-SDK   File: AbstractClient.java   Source Code and License Vote up 4 votes
@Override
public SdkProto invokeSync(SdkProto sdkProto, long timeoutMillis) throws RemotingConnectException,
        RemotingTimeoutException, InterruptedException, RemotingSendRequestException {
    final Channel channel = cf.channel();
    if (channel.isActive()) {
        final int rqid = sdkProto.getRqid();
        try {
            final ResponseFuture responseFuture = new ResponseFuture(rqid, timeoutMillis, null, null);
            asyncResponse.put(rqid, responseFuture);
            channel.writeAndFlush(sdkProto).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        //发送成功后立即跳出
                        responseFuture.setIsSendStateOk(true);
                        return;
                    }
                    // 代码执行到此说明发送失败,需要释放资源
                    asyncResponse.remove(rqid);
                    responseFuture.putResponse(null);
                    responseFuture.setCause(channelFuture.cause());
                    logger.warn("send a request command to channel <" + NettyUtil.parseRemoteAddr(channel) + "> failed.");
                }
            });
            // 阻塞等待响应
            SdkProto resultProto = responseFuture.waitResponse(timeoutMillis);
            if (null == resultProto) {
                if (responseFuture.isSendStateOk()) {
                    throw new RemotingTimeoutException(NettyUtil.parseRemoteAddr(channel), timeoutMillis,
                            responseFuture.getCause());
                } else {
                    throw new RemotingSendRequestException(NettyUtil.parseRemoteAddr(channel),
                            responseFuture.getCause());
                }
            }
            return resultProto;
        } catch (Exception e) {
            logger.error("invokeSync fail, addr is " + NettyUtil.parseRemoteAddr(channel), e);
            throw new RemotingSendRequestException(NettyUtil.parseRemoteAddr(channel), e);
        } finally {
            asyncResponse.remove(rqid);
        }
    } else {
        NettyUtil.closeChannel(channel);
        throw new RemotingConnectException(NettyUtil.parseRemoteAddr(channel));
    }
}
 
Example 18
Project: sds   File: ServerServiceImpl.java   Source Code and License Vote up 4 votes
@Override
public boolean checkChannel(String uniqueKey) {
    Channel channel =  SocketManager.getInstance().getChannelByUniqueKey(uniqueKey);
    return channel!=null&&channel.isActive();
}
 
Example 19
Project: hadoop   File: SimpleHttpProxyHandler.java   Source Code and License Vote up 4 votes
private static void closeOnFlush(Channel ch) {
  if (ch.isActive()) {
    ch.writeAndFlush(Unpooled.EMPTY_BUFFER)
      .addListener(ChannelFutureListener.CLOSE);
  }
}
 
Example 20
Project: http-proxy-netty   File: HttpProxyClientHandler.java   Source Code and License Vote up 4 votes
private void flushAndClose(Channel ch) {
    if (ch != null && ch.isActive()) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}