package fr.zng.xxzx.netty;


import fr.zng.xxzx.util.ConvertUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;

import java.net.InetSocketAddress;

import javax.swing.JComponent;

public class OutboundHandler extends ChannelOutboundHandlerAdapter {
    
    private JComponent jc;
    
    //客户端ip地址
    private String ip = "";
    
    public OutboundHandler() {
    }
    
    public OutboundHandler(JComponent jc) {
        this.jc = jc;
    }
    // 向client发送消息
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
        throws Exception {
//         logger.info("OutboundHandler1.write");
        try {
            InetSocketAddress saddr = (InetSocketAddress) ctx.channel().remoteAddress();
            ip = saddr.toString();
            String response = (String) msg;
            ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
            encoded.writeBytes(ConvertUtil.HexStrToAscii(response));
            ctx.write(encoded);
            ctx.flush();
//            CommUtil.doPrint(jc, "向客户端ip " + ip + " 发送内容：", response);
            System.out.println("向客户端ip " + ip + " 发送内容："+ response);
        } finally {
            if (((ByteBuf) msg).refCnt() != 0) {
                ReferenceCountUtil.release(msg);
            }
        }
    }

}
