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接收消息
            inputStream = socket.getInputStream();
            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));
            outputStream = socket.getOutputStream();
            packet = packet.trim();
            // 处理数据包
             String ss = iClientDataPacketService.handleClientSendPacket(packet);
            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();
            }
        }
    }
}
