package com.inspect.patrol.linkage.handler;

import com.inspect.base.core.utils.HexUtils;
import com.inspect.base.core.utils.SpringUtils;
import com.inspect.patrol.linkage.NettyUdpServer;
import com.inspect.patrol.linkage.processor.ReceiveProcessor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);

    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        ByteBuf byteBuf = packet.content();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.getBytes(0, bytes);
        ReceiveProcessor bean = SpringUtils.getBean(ReceiveProcessor.class);
        System.out.println("============有udp请求:" + HexUtils.binary(bytes, 16));
        bean.parse(bytes);
        String resStr = "ok";
        byte[] resBytes = resStr.getBytes("GB2312");
        DatagramPacket resData = new DatagramPacket(Unpooled.copiedBuffer(resBytes), (InetSocketAddress) packet.sender());
        ctx.writeAndFlush(resData);
    }
}
