伪异步IO(1.一个连接对应一个线程池中的线程,避免频繁创建和释放线程 2.ThreadPoolExecutor核心线程池和阻塞队列的创建)

.
|-- client
|   `-- TimeClient.java
`-- server
    |-- TimeServer.java
    |-- TimerServerHandler.java
    `-- TimerServerHandlerExecutePool.java

TimeClient.java

package disguise_async_io.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TimeClient {
    public static void main(String[] args) {
        int port = 8080;

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            socket = new Socket("127.0.01", port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);


            while (true) {
                try {
                    // 向服务器发送数据
                    out.println("QUERY TIME ORDER");

                    // 收取服务器
                    String resp = in.readLine();

                    System.out.println("now time is:" + resp);

                    // 每秒发送一次查询请求
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
                out = null;
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                socket = null;
            }
        }
    }
}

/*
now time is:Thu Jul 09 00:15:23 CST 2020
 */

TimeServer.java

package disguise_async_io.server;

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

public class TimeServer {
    public static void main(String[] args) throws IOException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        ServerSocket server = null;

        try {
            server = new ServerSocket(port);
            System.out.println("timer server start at port:" + port);
            Socket socket = null;

            TimerServerHandlerExecutePool singleExecutor = new TimerServerHandlerExecutePool(50, 10000);

            while (true) {
                socket = server.accept();
                // new Thread(new TimerServerHandler(socket)).start();

                // 改为线程池处理
                singleExecutor.execute(new TimerServerHandler(socket));

            }
        } finally {
            if (server != null) {
                System.out.println("time server close~");
                server.close();
                server = null;
            }
        }
    }
}
TimerServerHandlerExecutePool.java
package disguise_async_io.server;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TimerServerHandlerExecutePool {
    private ExecutorService executor;

    public TimerServerHandlerExecutePool(int maxPoolSize, int queueSize) {
        executor = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(), // 核心数量
                maxPoolSize,
                120L, // 120s
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(queueSize));
    }

    public void execute(Runnable task) {
        executor.execute(task);
    }
}
TimerServerHandler.java
package disguise_async_io.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

public class TimerServerHandler implements Runnable {
    private Socket socket;

    public TimerServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime = null;
            String body = null;
            while (true) {

                // 直接读取客户端发送的字符串
                body = in.readLine();
                if (body == null) {
                    break;
                }

                System.out.println("timer server recv:" + body);
                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";

                // 发送给客户端
                out.println(currentTime);
            }
        } catch (IOException e) {
            if (in != null) {
                try {
                    in.close();
                    in = null;
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

            if (out != null) {
                out.close();
                out = null;
            }

            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                this.socket = null;
            }
        }
    }
}

/*
timer server start at port:8080
timer server recv:QUERY TIME ORDER
 */

 

 

 

 

你可能感兴趣的:(【netty】)