/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/10/27
 */
package org.ts.ddcs.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ts.ddcs.util.BytesUtil;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/***
 * Date:2022/10/27
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
public class TestController {
    @GetMapping(value = "collect/test")
    public String toTest() {
        try {
            // 1.定义服务器的地址、端口号、数据
            InetAddress address = InetAddress.getByName("localhost");
            // 2.定义服务器端口
            int port = 8002;

            // 3.创建发送端对象：发送端自带默认端口号
            DatagramSocket socket = new DatagramSocket(2222);

            // 4.客户端启动成功，输出提示信息
            System.out.println("****客户端启动成功****");
            String msg ="7E7E01005128290300002F20080230522230271439160396987E7E01005128290300002F0008023052221027144016034F497E7E01005128290300002F0008023052221027144116038F187E7E01005128290300002F0008023052221027144216038FE87E7E01005128290300002F0008023052221027144316034FB97E7E01005128290300002F0008023052221027144416038E087E7E01005128290300002F0008023052221027144516034E597E7E01005128290300002F0008023052221027144616034EA97E7E01005128290300002F0008023052221027144716038EF8";
            byte[] buffer= BytesUtil.hexStr2Bytes(msg);

            DatagramPacket packets = new DatagramPacket(buffer, buffer.length, address, port);
            // 5.4 发送数据出去
            socket.send(packets);

            while (true) {
                byte[] buf = new byte[1024 * 64];
                DatagramPacket packet = new DatagramPacket(buf, buf.length);
                // 6.2 接收服务器响应的数据
                socket.receive(packet);
                // 6.3 取出数据
                int len = packet.getLength();
                if (len >0) {
                    String rs = new String(buf, 0, len);
                    System.out.println("收到了ip为：" + packet.getAddress() + " 端口号为：" + packet.getPort() + "的消息：" + rs);
                    break;
                }
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "ok";
    }
}
