package com.uavps.framework.udp;

import org.springframework.stereotype.Component;

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

/**
 * @Author MBQ
 * @Date: 2025/1/9
 * @Description:
 * @Version: 1.0
 **/
@Component
public class UdpClientService {

    public void send(String message) {
        try {
            //创建客户端对象，随机一个端口
            DatagramSocket socket = new DatagramSocket();
            System.out.println("udp客户端发送数据：" + message);

            //封装数据
            byte[] data = message.getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), 9010);

            //发送数据
            socket.send(packet);

            //释放资源
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
