package com.imdroid.ntripproxy.service;

import com.imdroid.common.util.DataTypeUtil;
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 "+this.host + ":" + this.port);
            this.socket = new DatagramSocket();
            this.inetAddress = InetAddress.getByName(this.host);
        } catch (Exception e) {
            logger.error("初始化udp客户端失败：", e);
        }
    }

    public void send(byte[] data) {
        try {
            DatagramPacket packet = new DatagramPacket(data, data.length, inetAddress, port);
            socket.send(packet);
        } catch (Exception e) {
            logger.error("推送异常:", e);
        }
    }

    public void sendWithDebug(byte[] data) {
        if (logger.isDebugEnabled()) {
            logger.debug("推送udp {}: {}", port, DataTypeUtil.getHexString(data));
        }
        send(data);
    }
}
