package com.huimv.datacollection.tcp;


import com.huimv.datacollection.service.IClientDataPacketService;

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

/**
 * @author yinhao
 * @version 1.0
 * @date 2021/07/07 17:32
 */
public class ServerThread extends Thread {

    private Socket socket;

    private IClientDataPacketService iClientDataPacketService;

    public  ServerThread(Socket socket, IClientDataPacketService iClientDataPacketService) {
        this.socket = socket;
        this.iClientDataPacketService = iClientDataPacketService;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {

            // server接收消息
            inputStream = socket.getInputStream();
            byte[] b = new byte[1024];
            inputStream.read(b);
            String packet = new String(b);
            packet = packet.trim();
            System.out.println(packet);
            // 处理数据包
            String backPackage = iClientDataPacketService.handleClientSendPacket(packet);
            System.out.println(backPackage);

            if (backPackage != null) {
                outputStream = socket.getOutputStream();
                outputStream.write(backPackage.getBytes());
                outputStream.flush();
            }

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