package com.huimv.acquisition.socket;
import com.huimv.acquisition.socket.eartagrecive.service.IClientDataPacketService;

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

//@Component
public class ServerThread extends Thread {

    private Socket socket;
   // @Autowired
    private IClientDataPacketService iClientDataPacketService;
    public ServerThread(Socket socket, IClientDataPacketService iClientDataPacketService) {
        this.socket = socket;
        this.iClientDataPacketService = iClientDataPacketService;
    }
    //空数据包会出问题----解决
    @Override
    public void run() {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        PrintWriter printWriter = null;

        try {
            // server接收消息 应该如何处理   如果数据为空
            socket.setSoTimeout(20000);
            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            inputStream.read(b);
            String packet = new String(b);
            int i = packet.indexOf("+", packet.indexOf("+") + 1);
            //int ver = Integer.parseInt(packet.substring(i + 1, i + 2));
            packet = packet.trim();
            // 处理数据包
            outputStream = socket.getOutputStream();
            String ss = iClientDataPacketService.handleClientSendPacket(packet);
            if(ss!=null){
                outputStream.write(ss.getBytes());
            }

            socket.shutdownInput();

        } catch (IOException | ParseException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (printWriter != null) {
                    printWriter.close();
                }
                if (outputStream != null) {
                    outputStream.close();

                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}