package com.yx.face.netty_client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: face-server
 * @Package: com.yx.face.nettyserver
 * @ClassName: RequestClientHandler
 * @Author: 崔哥
 * @Description: 自定义业务处理handler
 * @Date: 2021/11/22 13:14
 * @Version: 1.0
 */
@Slf4j
public class RequestClientHandler extends ChannelInboundHandlerAdapter {

    private String param;
    private NettyChannelInitializer nettyChannelInitializer;

    public RequestClientHandler(String param, NettyChannelInitializer nettyChannelInitializer) {
        this.param = param;
        this.nettyChannelInitializer = nettyChannelInitializer;
    }

    /**
     * 客户端连接上服务端之后会调用此方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("****channelActive成功****接收的参数为::" + param);
        ctx.writeAndFlush(param);
    }

    /**
     * 客户端读取服务端写入的数据
     *
     * @param ctx
     * @param obj
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        if (null != obj) {
            log.info("Receive server response : [" + obj.toString() + "]");
        }
        nettyChannelInitializer.setResponse(obj.toString());
    }

    /**
     * 连接或者发送读取数据出现异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}
