Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:co.rsk.net.eth.RskWireProtocol.java

License:Open Source License

/*************************
 *  Message Processing   */*from w w  w . j a  v  a 2s.  co m*/
 *************************/

protected void processStatus(org.ethereum.net.eth.message.StatusMessage msg, ChannelHandlerContext ctx)
        throws InterruptedException {

    try {
        Genesis genesis = GenesisLoader.loadGenesis(config.genesisInfo(),
                config.getBlockchainConfig().getCommonConstants().getInitialNonce(), true);
        if (!Arrays.equals(msg.getGenesisHash(), genesis.getHash())
                || msg.getProtocolVersion() != version.getCode()) {
            loggerNet.info("Removing EthHandler for {} due to protocol incompatibility",
                    ctx.channel().remoteAddress());
            ethState = EthState.STATUS_FAILED;
            disconnect(ReasonCode.INCOMPATIBLE_PROTOCOL);
            ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol
            return;
        }

        if (msg.getNetworkId() != config.networkId()) {
            ethState = EthState.STATUS_FAILED;
            disconnect(ReasonCode.NULL_IDENTITY);
            return;
        }

        // basic checks passed, update statistics
        channel.getNodeStatistics().ethHandshake(msg);
        ethereumListener.onEthStatusUpdated(channel, msg);

        if (peerDiscoveryMode) {
            loggerNet.debug("Peer discovery mode: STATUS received, disconnecting...");
            disconnect(ReasonCode.REQUESTED);
            ctx.close().sync();
            ctx.disconnect().sync();
            return;
        }
    } catch (NoSuchElementException e) {
        loggerNet.debug("EthHandler already removed");
    }
}

From source file:co.rsk.rpc.netty.RskJsonRpcHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    emitter.unsubscribe(ctx.channel());
    super.channelInactive(ctx);
}

From source file:co.rsk.rpc.netty.RskJsonRpcHandler.java

License:Open Source License

@Override
public JsonRpcResultOrError visit(EthSubscribeRequest request, ChannelHandlerContext ctx) {
    EthSubscribeTypes subscribeType = request.getParams().getSubscription();
    switch (subscribeType) {
    case NEW_HEADS:
        return emitter.subscribe(ctx.channel());
    default://from  w  ww  . ja  va 2 s  .c o m
        LOGGER.error("Subscription type {} is not implemented", subscribeType);
        return new JsonRpcInternalError();
    }
}

From source file:co.rsk.rpc.netty.RskJsonRpcHandlerTest.java

License:Open Source License

@Test
public void visitSubscribe() {
    Channel channel = mock(Channel.class);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(channel);
    when(emitter.subscribe(channel)).thenReturn(SAMPLE_SUBSCRIPTION_ID);

    assertThat(handler.visit(SAMPLE_SUBSCRIBE_REQUEST, ctx), is(SAMPLE_SUBSCRIPTION_ID));
}

From source file:co.rsk.rpc.netty.RskJsonRpcHandlerTest.java

License:Open Source License

@Test
public void handlerDeserializesAndHandlesRequest() throws Exception {
    Channel channel = mock(Channel.class);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.channel()).thenReturn(channel);

    when(serializer.deserializeRequest(any())).thenReturn(SAMPLE_SUBSCRIBE_REQUEST);
    when(emitter.subscribe(channel)).thenReturn(SAMPLE_SUBSCRIPTION_ID);
    when(serializer.serializeMessage(any())).thenReturn("serialized");

    DefaultByteBufHolder msg = new DefaultByteBufHolder(Unpooled.copiedBuffer("raw".getBytes()));
    handler.channelRead(ctx, msg);/*from w ww. ja  v a  2  s  .c  o m*/

    verify(ctx, times(1)).writeAndFlush(new TextWebSocketFrame("serialized"));
    verify(ctx, never()).fireChannelRead(any());
}

From source file:code.google.nfs.rpc.netty.client.NettyClientHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof List) {
        @SuppressWarnings("unchecked")
        List<ResponseWrapper> responses = (List<ResponseWrapper>) msg;
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug("receive response list from server: " + ctx.channel().remoteAddress()
                    + ",list size is:" + responses.size());
        }/*from w w w  .j  a  v  a  2 s.co m*/
        client.putResponses(responses);
    } else if (msg instanceof ResponseWrapper) {
        ResponseWrapper response = (ResponseWrapper) msg;
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug("receive response list from server: " + ctx.channel().remoteAddress() + ",request is:"
                    + response.getRequestId());
        }
        client.putResponse(response);
    } else {
        LOGGER.error("receive message error,only support List || ResponseWrapper");
        throw new Exception("receive message error,only support List || ResponseWrapper");
    }
}

From source file:code.google.nfs.rpc.netty.client.NettyClientHandler.java

License:Apache License

public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    LOGGER.warn("connection closed: " + ctx.channel().remoteAddress());
    factory.removeClient(key, client);//from w  ww  .j  av a2s .  com
}

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    if (decodeWasNull) {
        decodeWasNull = false;//from w w w.j a v  a 2  s. co  m
        if (!ctx.channel().config().isAutoRead()) {
            ctx.read();
        }
    }
    ctx.fireChannelReadComplete();
}

From source file:code.google.nfs.rpc.netty.server.NettyServerHandler.java

License:Apache License

private void sendErrorResponse(final ChannelHandlerContext ctx, final RequestWrapper request) {
    ResponseWrapper responseWrapper = new ResponseWrapper(request.getId(), request.getCodecType(),
            request.getProtocolType());/*from   www.  j  a  v a 2 s  .  c o m*/
    responseWrapper.setException(
            new Exception("server threadpool full,maybe because server is slow or too many requests"));
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + request.getId());
            }
        }
    });
}

From source file:code.google.nfs.rpc.netty4.client.Netty4ClientHandler.java

License:Apache License

public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    LOGGER.warn("connection closed: " + ctx.channel().remoteAddress());
    factory.removeClient(key, client);/* ww w. j  a va2 s  .  com*/
}