package com.yutou.tools.services;

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

public class ServerManager {
    private static ServerManager manager;
    private ServerSocket server;
    private ServerManager(){
        try {
            server=new ServerSocket(8100);
            while (true){
                new MyThread(server.accept());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void restart(){
        try {
            server.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            server=new ServerSocket(8100);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private OutputStream nasOutPutStream;
    private InputStream nasInputStream;
    public static ServerManager getManager() {
        if(manager==null){
            manager=new ServerManager();
        }
        return manager;
    }
    public void send(String msg){
        if(nasOutPutStream!=null){
            try {
                nasOutPutStream.write(msg.getBytes());
                nasOutPutStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private class MyThread extends  Thread{
        Socket socket;
        private MyThread(Socket socket){
            this.socket=socket;
            start();
        }

        @Override
        public void run() {
            super.run();
            try {
                nasOutPutStream=socket.getOutputStream();
                nasInputStream=socket.getInputStream();
                BufferedReader reader=new BufferedReader(new InputStreamReader(nasInputStream));
                String tmp,str="";
                while (true){
                 tmp=reader.readLine();
                 if(tmp!=null){
                     System.out.println(tmp);
                 }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            nasOutPutStream=null;
            nasInputStream=null;
        }

    }
}
