package net.vtstar.zhongtong.avi.gateway.stamping.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @Author: xiadongwei
 * @Date: 2020/4/8 17:15
 */
@Slf4j
public class ClientSocketUtil {

    static Socket server;
    static Integer port = 62944;

    public static void main (String[] s){
        while (true){
            send("10.1.25.178", "P101");
            send("10.1.25.178", "P102");
            send("10.1.25.178", "P107");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static String send(String ip, String data){
        //TODO: 暂时不读P102的值
        if ("P102".equals(data)){
            return "0";
        }
        //连接服务端
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            server = new Socket(ip, port);
            //向服务端写入数据
            osw = new OutputStreamWriter(server.getOutputStream());
            bw = new BufferedWriter(osw);
            //<get><var>.P107</var><auto>yes</auto></get>
            bw.write("<get><var>." + data + "</var><auto>yes</auto></get>\r\n");
            bw.flush();
            isr = new InputStreamReader(server.getInputStream());
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            sb.append(br.readLine());
            String result = sb.toString();
            log.info("大族激光读取结果:{}", result);
            if (result.contains("err")){
                return "0";
            }else{
                return result.replace("<get><." + data + ">", "")
                        .replace("</." + data + "><auto>yes</auto></get>", "");
            }
        } catch (Exception e) {
            log.error("连接异常!");
        }finally {
            try {
                if (null != osw) {
                    osw.close();
                }
                if (null != bw) {
                    bw.close();
                }
                if (null != isr) {
                    isr.close();
                }
                if (null != br) {
                    br.close();
                }
                if (null != server && server.isConnected()) {
                    server.close();
                }
            } catch (IOException e) {
                log.error("连接异常!");
            }
        }
        return "0";
    }
}
