package com.huimv.acquisition.socket;

import com.huimv.acquisition.socket.eartagrecive.service.IClientDataPacketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;


@Component
public class Server implements CommandLineRunner {

    @Autowired
    private IClientDataPacketService iClientDataPacketService;

    @Override
    public void run(String... args) throws Exception {
        try {
            // 初始化服务端socket连接， 并监听8888端口的socket请求
            ServerSocket serverSocket = new ServerSocket(10022);
            System.out.println("****** I am Server ,port  10022, now begin to wait the client ******");
            int count = 0;
            // 处理socket请求
            Socket socket = null;
            while (true) {
                socket = serverSocket.accept();
                ServerThread serverThread = new ServerThread(socket, iClientDataPacketService);
                System.out.println("client host address is: " + socket.getInetAddress().getHostAddress());
                serverThread.start();
                count++;
                System.out.println("now client count is: " + count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



//测试发送数据
    public static void main(String[] args) throws IOException {
            //建立socket向服务器发送连接请求
            Socket socket = new Socket("127.0.0.1", 9090);
            InputStream inputStream;
            inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            //客户端向socket发送数据
            PrintWriter printWriter = new PrintWriter(outputStream);
            //printWriter.println("zj+202007239999893+133070303805451+86+0+2031+0+93+20211111153254+1.0#1.0#11600+0+end");    //没有注册
            //printWriter.println("hm+869401040126203+0+7+end");//没有注册
            //printWriter.println("zj+202007239999892+133070300000099+77+0+0+0+96+2021109916" + i +"33+1.0#1.0#9383+0+end");
            //printWriter.println("hm+158+4+1+289+20170208152300+6+end");
            printWriter.flush();
            //读取数据
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String readLine = bufferedReader.readLine();
            System.out.println(readLine);
            inputStream.close();
            outputStream.close();
            socket.close();

    }
}
