package com.imdroid.beidou_fwd.service;

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

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

public class UDPClient {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private DatagramSocket socket;

    private InetAddress inetAddress;

    private String host;

    private int port;

    public void init(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            logger.info("UDP client init "+host + ":" + port);
            this.socket = new DatagramSocket();
            this.inetAddress = InetAddress.getByName(host);
        } catch (Exception e) {
            logger.error("初始化udp客户端失败：", e);
        }
    }

    public void sendMessage(String msg) {
        try {
            logger.info("udp推送gnss数据:{}", msg);
            byte[] data = msg.getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length, inetAddress, port);
            socket.send(packet);
        } catch (Exception e) {
            logger.error("udp推送gnss数据异常:", e);
        }
    }
}
