package com.yfd.platform.component.nettyudpserver;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * netty服务器，主要用于与客户端通讯
 */

public class NettyUdpServer {
   private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);
    private static final int MAX_FRAME_LENGTH = 1024 * 1024;  //最大长度
    private static final int LENGTH_FIELD_LENGTH = 1;  //长度字段所占的字节数
    private static final int LENGTH_FIELD_OFFSET = 0;  //长度偏移
    private static final int LENGTH_ADJUSTMENT = 0;
    private static final int INITIAL_BYTES_TO_STRIP = 1;

    private final EventLoopGroup group;
    private final Bootstrap bootstrap;

    public NettyUdpServer(int port) throws Exception {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST,true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        //加入自己的业务处理handler
                        pipeline.addLast(new NettyUdpHandler());
                    }
                }).localAddress(new InetSocketAddress(port));
        logger.info("Netty Udp server is started!（port:" + port + "）");
    }

    public Channel bind(){
        return bootstrap.bind().syncUninterruptibly().channel();
    }

    public void stop(){
        group.shutdownGracefully();
    }

    public static void main(String[] args) throws Exception{
        NettyUdpServer server = new NettyUdpServer(9300);
        try {
            Channel channel = server.bind();
            logger.info("NettyUdpServer running");
            channel.closeFuture().sync();
        }finally {
            server.stop();
        }
    }
}

