5.伪异步I/O编程

样例:

1.定义一个线程池处理类:
    public class HandlerSocketServerPool {
        private ExecutorService executorService;

        public HandlerSocketServerPool() {
            this.executorService = new ThreadPoolExecutor(3, 10, 120, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
        }

        public  void execute(Runnable socketHandler){
            executorService.execute(socketHandler);
        }
    }
    
2.定义线程处理类:
    public class ServerThreadReader implements Runnable{
        private Socket socket;
        public ServerThreadReader(Socket socket) {
            this.socket = socket;
        }
        public void run() {
            //3.从Socket管道中得到一个字节输入流对象
            InputStream inputStream= null;
            try {
                inputStream = socket.getInputStream();
                //4.把字节输入流包装称一个缓冲字符输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                String msg;
                while ((msg = br.readLine()) != null) {
                    System.out.println("服务端线程:"+Thread.currentThread().getName()+"接收到的消息:" + msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
3.server启动类:
    public class Server {
        public static void main(String[] args) {
            try {
                System.out.println("======服务端启动=======");
                //1.定义一个ServerSocket对象进行服务端的端口注册
                ServerSocket ss=new ServerSocket(9999);
                HandlerSocketServerPool socketServerPool=new HandlerSocketServerPool();
                System.out.println("======服务端等待连接.......");
                while (true){
                    //2.监听客户端的Socket连接请求
                    Socket socket = ss.accept();
                    //重点1:这里通过线程池执行方法
                    socketServerPool.execute(new ServerThreadReader(socket));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
4.客户端类
    public class Client {
        public static void main(String[] args) {
            try {
                //1.创建Socket对象请求服务端的连接
                Socket client = new Socket("127.0.0.1", 9999);
                //2.从Scoket对象中获取一个字节输出流
                OutputStream outputStream = client.getOutputStream();
                //3.把字节流包装成一个打印流
                PrintStream ps = new PrintStream(outputStream);
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    System.out.print("客户端--->请讲:");
                    String msg = scanner.nextLine();
                    ps.println(msg);
                    ps.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

小结:

posted @ 2022-08-09 21:13  努力的达子  阅读(18)  评论(0编辑  收藏  举报