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.*;
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) throws SocketException {
        SocketClient socketClient = new SocketClient();
        //socketClient.processTcp(0, 0);
        socketClient.processUdp(10001, 2);
    }

    @Async
    public void processUdp(int port, int type) throws SocketException {
        if (type < 0) type = 0;
        if (type >= testFilePath.length) type -= 1;
        DatagramSocket datagramSocket = new DatagramSocket();
        try {
            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);
                datagramSocket.send(new DatagramPacket(b, b.length,InetAddress.getLocalHost(), port));
                TimeUnit.MILLISECONDS.sleep(200);
            }
            datagramSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    public void processTcp(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();
        }
    }
}

