Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

From source file:alluxio.worker.netty.UnsupportedMessageHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
    if (object instanceof RPCProtoMessage) { // Unknown proto message, reply proto.
        RPCProtoMessage resp = RPCProtoMessage
                .createResponse(new UnimplementedException("Unrecognized RPC: " + object));
        ctx.writeAndFlush(resp);//from  w ww .ja v a 2  s  .  c o m
    } else { // Unknown message, this should not happen.
        ctx.fireChannelRead(object);
    }
}

From source file:blazingcache.network.netty.DataMessageDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;//from ww  w .j a  v  a 2s.  co m
    try {
        ctx.fireChannelRead(DodoMessageUtils.decodeMessage(in));
    } finally {
        ReferenceCountUtil.release(msg);
    }

}

From source file:books.netty.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????//from w  w  w.  jav  a2 s.  co  m
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:books.netty.protocol.netty.client.LoginAuthReqHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * <p>//ww w  .j  ava 2s . c o m
 * Sub-classes may override this method to change behavior.
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ??????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        byte loginResult = (byte) message.getBody();
        if (loginResult != (byte) 0) {
            // ?
            ctx.close();
        } else {
            System.out.println("Login is ok : " + message);
            ctx.fireChannelRead(msg);
        }
    } else
        ctx.fireChannelRead(msg);
}

From source file:books.netty.protocol.netty.server.HeartBeatRespHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?/*from w  w w  . j  a v a2 s . c om*/
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
        System.out.println("Receive client heart beat message : ---> " + message);
        NettyMessage heartBeat = buildHeatBeat();
        System.out.println("Send heart beat response message to client : ---> " + heartBeat);
        ctx.writeAndFlush(heartBeat);
    } else
        ctx.fireChannelRead(msg);
}

From source file:books.netty.protocol.netty.server.LoginAuthRespHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to
 * the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * <p>//from w  ww  . java 2 s . c  o  m
 * Sub-classes may override this method to change behavior.
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
        String nodeIndex = ctx.channel().remoteAddress().toString();
        NettyMessage loginResp = null;
        // ???
        if (nodeCheck.containsKey(nodeIndex)) {
            loginResp = buildResponse((byte) -1);
        } else {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            String ip = address.getAddress().getHostAddress();
            boolean isOK = false;
            for (String WIP : whitekList) {
                if (WIP.equals(ip)) {
                    isOK = true;
                    break;
                }
            }
            loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
            if (isOK)
                nodeCheck.put(nodeIndex, true);
        }
        System.out.println("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:cc.agentx.client.net.nio.Socks5Handler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksRequest request) throws Exception {
    switch (request.protocolVersion()) {
    case SOCKS4a:
        log.warn("\tBad Handshake! (protocol version not supported: 4)");
        ctx.write(new SocksInitResponse(SocksAuthScheme.UNKNOWN));
        if (ctx.channel().isActive()) {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }/*from   w  ww  .j av a2 s  .  c  o  m*/
        break;
    case SOCKS5:
        switch (request.requestType()) {
        case INIT:
            ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
            ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH));
            break;
        case AUTH:
            ctx.pipeline().addFirst(new SocksCmdRequestDecoder());
            ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS));
            break;
        case CMD:
            if (((SocksCmdRequest) request).cmdType() == SocksCmdType.CONNECT) {
                ctx.pipeline().addLast(new XConnectHandler());
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(request);
            } else {
                ctx.close();
                log.warn("\tBad Handshake! (command not support: {})", ((SocksCmdRequest) request).cmdType());
            }
            break;
        case UNKNOWN:
            log.warn("\tBad Handshake! (unknown request type)");
        }
        break;
    case UNKNOWN:
        log.warn("\tBad Handshake! (protocol version not support: {}", request.protocolVersion());
        ctx.close();
        break;
    }
}

From source file:cc.blynk.core.http.handlers.UploadHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (!accept(ctx, req)) {
            ctx.fireChannelRead(msg);
            return;
        }//from w  w w.ja  v  a 2 s . c  om

        try {
            log.debug("Incoming {} {}", req.method(), req.uri());
            decoder = new HttpPostRequestDecoder(factory, req);
        } catch (ErrorDataDecoderException e) {
            log.error("Error creating http post request decoder.", e);
            ctx.writeAndFlush(badRequest(e.getMessage()));
            return;
        }

    }

    if (decoder != null && msg instanceof HttpContent) {
        // New chunk is received
        HttpContent chunk = (HttpContent) msg;
        try {
            decoder.offer(chunk);
        } catch (ErrorDataDecoderException e) {
            log.error("Error creating http post offer.", e);
            ctx.writeAndFlush(badRequest(e.getMessage()));
            return;
        } finally {
            chunk.release();
        }

        // example of reading only if at the end
        if (chunk instanceof LastHttpContent) {
            Response response;
            try {
                String path = finishUpload();
                if (path != null) {
                    response = afterUpload(ctx, path);
                } else {
                    response = serverError("Can't find binary data in request.");
                }
            } catch (NoSuchFileException e) {
                log.error("Unable to copy uploaded file to static folder. Reason : {}", e.getMessage());
                response = (serverError());
            } catch (Exception e) {
                log.error("Error during file upload.", e);
                response = (serverError());
            }
            ctx.writeAndFlush(response);
        }
    }
}

From source file:cc.blynk.integration.model.websocket.AppWebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();/*  w  ww . j  ava  2 s  . c o  m*/
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    if (msg instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        log.trace("WebSocket Client received message: " + frame.content());
        ctx.fireChannelRead(((WebSocketFrame) msg).retain());
    } else if (msg instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}

From source file:cc.blynk.integration.model.websocket.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();//from   w w w.  j a  va 2s  .c om
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        log.trace("WebSocket Client received message: " + binaryFrame.content());
        ctx.fireChannelRead(binaryFrame.retain().content());
    } else if (frame instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}