package com.hw.common.core.utils;

import com.alibaba.fastjson2.JSONObject;

import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @ProjectName:HwMes
 * @Author:xins
 * @Date:2024-04-12 13:43
 * @Version:1.0
 */
public class SocketUtils {

    public static String sendAndReceive(String host,int port,int readTimeout,String sendMessage) {

        Socket socket = null;
        try {
            socket = new Socket(host, port);
            OutputStream outToServer = socket.getOutputStream();
            byte[] sendMessageBytes = sendMessage.getBytes();
            outToServer.write(sendMessageBytes);
            outToServer.flush();
            socket.setSoTimeout(readTimeout);

            try  {
                // 获取Socket的输入流
                InputStream inFromServer = socket.getInputStream();

                // 创建一个足够大的缓冲区来接收数据
                byte[] buffer = new byte[1024];

                // 从输入流中读取数据
                int bytesRead;
                while ((bytesRead = inFromServer.read(buffer)) != -1) {
                    // 处理接收到的数据
                    String receivedMessage = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
                    System.out.println("Received feedback from server: " + receivedMessage);
                    return receivedMessage;
                }
            } catch (SocketTimeoutException e) {
                System.err.println("Reading from the socket timed out.");
            }
        } catch (IOException e) {
            System.err.println("An I/O error occurred: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close(); // 在异常情况下也尝试关闭
                } catch (IOException e) {
                    System.err.println("Failed to close the socket: " + e.getMessage());
                }
            }
        }

        return "";
    }

    public static void main(String[] args) {
        JSONObject assignTaskMessageJson = new JSONObject();
        assignTaskMessageJson.put("stationNo", 3);
        assignTaskMessageJson.put("time", System.currentTimeMillis());
        assignTaskMessageJson.put("materialBarcode", "1111");
        String host = "10.11.41.121";
        int port = 5000;
        int readTimeout = 5000; // 读取超时时间，单位：毫秒
        sendAndReceive(host, port, readTimeout,assignTaskMessageJson.toString());
    }
}
