NettyClientHandler.java 1.7 KB
Newer Older
1
package github.javaguide.transport.netty.client;
S
shuang.kou 已提交
2 3 4 5 6 7 8 9 10 11

import github.javaguide.dto.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
12 13
 * 自定义客户端 ChannelHandler 来处理服务端发过来的数据
 *
S
shuang.kou 已提交
14
 * @author shuang.kou
15
 * @createTime 2020年05月25日 20:50:00
S
shuang.kou 已提交
16 17 18 19
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);

20 21 22
    /**
     * 读取服务端传输的消息
     */
S
shuang.kou 已提交
23 24 25
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
26
            logger.info(String.format("client receive msg: %s", msg));
S
shuang.kou 已提交
27
            RpcResponse rpcResponse = (RpcResponse) msg;
28
            // 声明一个 AttributeKey 对象,类似于 Map 中的 key
S
shuang.kou 已提交
29
            AttributeKey<RpcResponse> key = AttributeKey.valueOf("rpcResponse");
30 31 32 33 34
            /*
             * AttributeMap 可以看作是一个Channel的共享数据源
             * AttributeMap 的 key 是 AttributeKey,value 是 Attribute
             */
            // 将服务端的返回结果保存到 AttributeMap 上
S
shuang.kou 已提交
35 36 37 38 39 40 41
            ctx.channel().attr(key).set(rpcResponse);
            ctx.channel().close();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

42 43 44
    /**
     * 处理客户端消息发生异常的时候被调用
     */
S
shuang.kou 已提交
45 46
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
47
        logger.error("client catch exception:", cause);
S
shuang.kou 已提交
48 49 50 51 52
        cause.printStackTrace();
        ctx.close();
    }
}