package com.yeejoin.amos.boot.module.jcs.biz.audioToText;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * 模拟客户端发送数据
 */
@Component
public class SocketClient {
    private static final Logger logger = LoggerFactory.getLogger(SocketClient.class);
    private static final String[] testFilePath = {
            "D:\\ffmpeg-4.4-full_build-shared\\bin\\out3.pcm",
            "D:\\ffmpeg-4.4-full_build-shared\\bin\\out4.pcm",
            "D:\\ffmpeg-4.4-full_build-shared\\bin\\record1.pcm",
            "D:\\ffmpeg-4.4-full_build-shared\\bin\\record2.pcm",
    };

    public static void main(String[] args) {
        SocketClient socketClient = new SocketClient();
        socketClient.process(0, 0);
    }

    @Async
    public void process(int port, int type) {
        if (type < 0) type = 0;
        if (type >= testFilePath.length) type -= 1;

        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), port));
            OutputStream outputStream = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(testFilePath[type]));
            byte[] b = new byte[4096];
            int len;
            while ((len = fis.read(b)) > 0) {
                logger.info("send data pack length: " + len);
                outputStream.write(b);
                TimeUnit.MILLISECONDS.sleep(200);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

