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

The following examples show how to use io.netty.channel.Channel#attr() . 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: Netty4MessageChannelHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Transports.assertTransportThread();
    if (!(msg instanceof ByteBuf)) {
        ctx.fireChannelRead(msg);
        return;
    }
    final ByteBuf buffer = (ByteBuf) msg;
    final int remainingMessageSize = buffer.getInt(buffer.readerIndex() - TcpHeader.MESSAGE_LENGTH_SIZE);
    final int expectedReaderIndex = buffer.readerIndex() + remainingMessageSize;
    try {
        Channel channel = ctx.channel();
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        // netty always copies a buffer, either in NioWorker in its read handler, where it copies to a fresh
        // buffer, or in the cumulative buffer, which is cleaned each time so it could be bigger than the actual size
        BytesReference reference = Netty4Utils.toBytesReference(buffer, remainingMessageSize);
        Attribute<NettyTcpChannel> channelAttribute = channel.attr(Netty4Transport.CHANNEL_KEY);
        transport.messageReceived(reference, channelAttribute.get(), profileName, remoteAddress, remainingMessageSize);
    } finally {
        // Set the expected position of the buffer, no matter what happened
        buffer.readerIndex(expectedReaderIndex);
    }
}
 
Example 2
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnMessage(Channel channel, WebSocketFrame frame) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnMessage() != null) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnMessage().invoke(implement, methodMapping.getOnMessageArgs(channel, textFrame));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example 3
Source File: HttpLifecycleChannelHandler.java    From zuul with Apache License 2.0 6 votes vote down vote up
protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest request)
{
    // Only allow this method to run once per request.
    Channel channel = ctx.channel();
    Attribute<State> attr = channel.attr(ATTR_STATE);
    State state = attr.get();

    if (state == State.STARTED) {
        // This could potentially happen if a bad client sends a 2nd request on the same connection
        // without waiting for the response from the first. And we don't support HTTP Pipelining.
        LOG.error("Received a http request on connection where we already have a request being processed. " +
                "Closing the connection now. channel = " + channel.id().asLongText());
        channel.close();
        ctx.pipeline().fireUserEventTriggered(new RejectedPipeliningEvent());
        return false;
    }
    
    channel.attr(ATTR_STATE).set(State.STARTED);
    channel.attr(ATTR_HTTP_REQ).set(request);
    ctx.pipeline().fireUserEventTriggered(new StartEvent(request));
    
    return true;
}
 
Example 4
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnBinary(Channel channel, WebSocketFrame frame) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnBinary() != null) {
        BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame;
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnBinary().invoke(implement, methodMapping.getOnBinaryArgs(channel, binaryWebSocketFrame));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example 5
Source File: ChannelInfo.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static ChannelInfo getOrCreateClientChannelInfo(Channel channel) {
    Attribute<ChannelInfo> attribute = channel.attr(ChannelInfo.CLIENT_CHANNEL_KEY);
    ChannelInfo channelInfo = attribute.get();
    if (channelInfo == null) {
        channelInfo = new ChannelInfo();
        // 此时FastFutureStore单例对象已经在RpcClient创建时初始化过了
        channelInfo.setPendingRpc(FastFutureStore.getInstance(0));
        channelInfo.setChannel(channel);
        attribute.set(channelInfo);
    }
    return channelInfo;
}
 
Example 6
Source File: SocketControlImpl.java    From sds with Apache License 2.0 5 votes vote down vote up
@Override
public void bindKey(Channel ctx, String key) {
    Attribute<String> attr = ctx.attr(attributeKey);
    if(attr!=null){
        attr.set(key);
        //put delivery
        deliveryClient.putKey(getModelName(),getUniqueKey(ctx),key);
    }
}
 
Example 7
Source File: WebSocketSession.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Get httpSession from the properties bound in the pipe
 * @param channel channel
 * @return WebSocketSession
 */
public static WebSocketSession getSession(Channel channel){
    if(isChannelActive(channel)) {
        Attribute<WebSocketSession> attribute = channel.attr(CHANNEL_ATTR_KEY_SESSION);
        if(attribute != null){
            return attribute.get();
        }
    }
    return null;
}
 
Example 8
Source File: ChannelManager.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public void removeChannel(Channel channel) {
    Attribute<String> participant = channel.attr(PushChannelContextHolder.CLIENTNAME_KEY);
    String participantName = participant.get();
    if (StringUtils.isNotBlank(participantName)) {
        log.debug("channel is in active, remove from channel map");
        lock.writeLock().lock();
        try {
            innerStoreManager.removeChannel(channel);
        } finally {
            lock.writeLock().unlock();
        }
    }
}
 
Example 9
Source File: DefaultChannelStoreManager.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void removeChannel(Channel channel) {
    Attribute<String> participant = channel.attr(PushChannelContextHolder.CLIENTNAME_KEY);
    String participantName = participant.get();
    List<Channel> channelList = channelMap.get(participantName);
    channelList.remove(channel);
    channelSet.remove(channel);

}
 
Example 10
Source File: DefaultRegistry.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private static boolean attachPublishEventOnChannel(RegisterMeta meta, Channel channel) {
    Attribute<ConcurrentSet<RegisterMeta>> attr = channel.attr(C_PUBLISH_KEY);
    ConcurrentSet<RegisterMeta> registerMetaSet = attr.get();
    if (registerMetaSet == null) {
        ConcurrentSet<RegisterMeta> newRegisterMetaSet = new ConcurrentSet<>();
        registerMetaSet = attr.setIfAbsent(newRegisterMetaSet);
        if (registerMetaSet == null) {
            registerMetaSet = newRegisterMetaSet;
        }
    }

    return registerMetaSet.add(meta);
}
 
Example 11
Source File: TcpRepository.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
/**
 * 保存已激活的 Channel
 *
 * @param channel 已激活的 Channel
 */
public void activeChannel(Channel channel) {
    Attribute<Integer> key = channel.attr(AttributeKey.valueOf("ID"));
    int id = key.get();

    CHANNEL_ARRAY.set(id, channel);
    SENDING_MESSAGE_QUEUE.get(id).clear();
}
 
Example 12
Source File: TransportHelper.java    From journalkeeper with Apache License 2.0 5 votes vote down vote up
public static ChannelTransport getOrNewTransport(Channel channel, RequestBarrier requestBarrier) {
    Attribute<ChannelTransport> attr = channel.attr(TRANSPORT_CACHE_ATTR);
    ChannelTransport transport = attr.get();

    if (transport == null) {
        transport = newTransport(channel, requestBarrier);
        attr.set(transport);
    }

    return transport;
}
 
Example 13
Source File: DefaultRegistryServer.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private static boolean attachSubscribeEventOnChannel(RegisterMeta.ServiceMeta serviceMeta, Channel channel) {
    Attribute<ConcurrentSet<RegisterMeta.ServiceMeta>> attr = channel.attr(S_SUBSCRIBE_KEY);
    ConcurrentSet<RegisterMeta.ServiceMeta> serviceMetaSet = attr.get();
    if (serviceMetaSet == null) {
        ConcurrentSet<RegisterMeta.ServiceMeta> newServiceMetaSet = new ConcurrentSet<>();
        serviceMetaSet = attr.setIfAbsent(newServiceMetaSet);
        if (serviceMetaSet == null) {
            serviceMetaSet = newServiceMetaSet;
        }
    }

    return serviceMetaSet.add(serviceMeta);
}
 
Example 14
Source File: TransportHelper.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static ChannelTransport getOrNewTransport(Channel channel, RequestBarrier requestBarrier) {
    Attribute<ChannelTransport> attr = channel.attr(TRANSPORT_CACHE_ATTR);
    ChannelTransport transport = attr.get();

    if (transport == null) {
        transport = newTransport(channel, requestBarrier);
        if (!attr.compareAndSet(null, transport)) {
            transport = attr.get();
        }
    }

    return transport;
}
 
Example 15
Source File: BaseHandler.java    From jt808-netty with MIT License 5 votes vote down vote up
/**
 * 递增获取流水号
 * @return
 */
public short getSerialNumber(Channel channel){
    Attribute<Short> flowIdAttr = channel.attr(SERIAL_NUMBER);
    Short flowId = flowIdAttr.get();
    if (flowId == null) {
        flowId = 0;
    } else {
        flowId++;
    }
    flowIdAttr.set(flowId);
    return flowId;
}
 
Example 16
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private PojoMethodMapping getPojoMethodMapping(String path, Channel channel) {
    PojoMethodMapping methodMapping;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        Attribute<String> attrPath = channel.attr(PATH_KEY);
        attrPath.set(path);
        methodMapping = pathMethodMappingMap.get(path);
        if (methodMapping == null) {
            throw new RuntimeException("path " + path + " is not in pathMethodMappingMap ");
        }
    }
    return methodMapping;
}
 
Example 17
Source File: NettyChannel.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link NettyChannel} for given {@link Channel}, this method never return null.
 */
public static NettyChannel attachChannel(Channel channel) {
    Attribute<NettyChannel> attr = channel.attr(NETTY_CHANNEL_KEY);
    NettyChannel nChannel = attr.get();
    if (nChannel == null) {
        NettyChannel newNChannel = new NettyChannel(channel);
        nChannel = attr.setIfAbsent(newNChannel);
        if (nChannel == null) {
            nChannel = newNChannel;
        }
    }
    return nChannel;
}
 
Example 18
Source File: ChannelUtil.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static boolean setAttributeIfAbsent(Channel channel, Object o) {
    synchronized (channel) {
        Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE);
        if (attr == null || attr.get() == null) {
            channel.attr(DEFAULT_ATTRIBUTE).set(o);
            return true;
        }
        return false;
    }
}
 
Example 19
Source File: ChannelInfo.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
public static ChannelInfo getServerChannelInfo(Channel channel) {
    Attribute<ChannelInfo> attribute = channel.attr(ChannelInfo.SERVER_CHANNEL_KEY);
    return  attribute.get();
}
 
Example 20
Source File: ChannelUtils.java    From jforgame with Apache License 2.0 4 votes vote down vote up
public static IdSession getSessionBy(Channel channel) {
	Attribute<IdSession> sessionAttr = channel.attr(SESSION_KEY);
	return sessionAttr.get() ;
}