package com.mortals.httpclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class UDPClientApp {
    private static final int PACK_SIZE = 4096;
    private byte[] inbuf = new byte[PACK_SIZE];
    private DatagramPacket inpack = new DatagramPacket(inbuf, inbuf.length);
    private DatagramPacket outpack;


    public void init() throws IOException {
        try (DatagramSocket sock = new DatagramSocket()) {
            outpack = new DatagramPacket(new byte[0], 0,new InetSocketAddress(InetAddress.getByName("192.168.0.1"),7688));
            Scanner scan = new Scanner(System.in);
            while (scan.hasNextLine()) { // 键盘输入
                byte[] buf = scan.nextLine().getBytes(); // 捕获发送
                outpack.setData(buf);
                sock.send(outpack);

                sock.receive(inpack); // 阻塞等待接受
                System.out.println(new String(inbuf, 0, inpack.getLength())); // 打印回送内容
            }
        }
    }


    public static void main(String[] args) throws IOException {
       // new UDPClientApp().init();
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        bootstrap.group(workGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel ch) throws Exception {
                        ch.pipeline().addLast(new UDPClientHandler());
                    }
                });
        try {
            Channel channel = bootstrap.bind(8074).sync().channel();
            channel.closeFuture().sync().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}