package com.unis.detectionnum.server.utils;

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

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class SocketUtils {

    private static final Logger log = LoggerFactory.getLogger(SocketUtils.class);

    /**
     * 发送消息给客户端
     * @param socket socket
     * @param oders 命令
     * @return 十六进制的字符串
     * @throws IOException
     * @throws InterruptedException
     */
    public String sendRequest(Socket socket, String oders) throws IOException, InterruptedException {

        // 发送的16进制字符串
        byte[] bytes1 = DataUtils.hexStringToByteArray(oders);
        OutputStream os = socket.getOutputStream();
        os.write(bytes1);

        // 封装输入流（接受客户端得流）
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis = new DataInputStream(bis);
        byte[] bytes = new byte[1]; // 一次读取一个byte
        String ret = "";
        try {
            while (dis.read(bytes) != -1) {
                ret += DataUtils.bytesToHexString(bytes) + " ";

                if (dis.available() == 0) { // 一个请求
                    log.info(socket.getRemoteSocketAddress() + ":" + ret);
                    break;
                }
                if (ret == "") {
                    wait();
                }
            }
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            return null;
        }
        return ret;
    }

    /**
     * 测试本机端口是否被使用
     * @param port
     * @return
     */
    public static boolean isLocalPortUsing(int port){
        boolean flag = true;
        try {
            //如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }
    /***
     * 测试主机Host的port端口是否被使用
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean isPortUsing(String host,int port) throws UnknownHostException{
        boolean flag = false;
        InetAddress Address = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(Address,port);  //建立一个Socket连接
            flag = true;
        } catch (IOException e) {

        }
        return flag;
    }

}
