博客
关于我
一个简单的伪异步IO程序
阅读量:257 次
发布时间:2019-03-01

本文共 4556 字,大约阅读时间需要 15 分钟。

伪异步IO通信模型示例

服务端代码

服务端代码实现了一个时间服务器,通过线程池处理多个客户端连接,解决了传统同步阻塞IO的性能问题。以下是服务端代码的主要实现细节:

public class TimeServer {    public static void main(String[] args) throws IOException {        ServerSocket server = null;        try {            server = new ServerSocket(8080);            Socket socket = null;            // 创建线程池            TimeServerHandlerExecutePool executePool = new TimeServerHandlerExecutePool(50, 10000);            while (true) {                socket = server.accept();                executePool.execute(new TimeServerHandler(socket));            }        } catch (Exception e) {            System.out.println("创建serverSocket失败,端口:" + 8080);            e.printStackTrace();        } finally {            System.out.println("The time server close");            if (server != null) {                server.close();            }        }    }}

TimeServerHandler

TimeServerHandler类实现了Runnable接口,负责处理客户端的连接和请求。以下是类的实现细节:

public class TimeServerHandler implements Runnable {    private Socket socket;    public TimeServerHandler(Socket socket) {        this.socket = socket;    }    public void run() {        BufferedReader in = null;        PrintWriter out = null;        try {            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));            out = new PrintWriter(socket.getOutputStream(), true);            String currentTime;            String body;            while (true) {                body = in.readLine();                if (null == body) {                    break;                }                System.out.println("The time server receive order : " + body);                if ("QUERY TIME ORDER".equalsIgnoreCase(body)) {                    currentTime = new Date(System.currentTimeMillis()).toString();                } else {                    currentTime = "BAD ORDER";                }                out.println(currentTime);            }        } catch (IOException e) {            System.out.println("exception");            e.printStackTrace();            if (in != null) {                try {                    in.close();                } catch (IOException e1) {                    e1.printStackTrace();                }            }            if (out != null) {                out.close();            }            if (this.socket != null) {                try {                    this.socket.close();                } catch (IOException e1) {                    e1.printStackTrace();                }            }        }    }}

TimeServerHandlerExecutePool

TimeServerHandlerExecutePool类通过ThreadPoolExecutor管理线程池,确保线程资源得到合理分配和管理。以下是类的实现细节:

public class TimeServerHandlerExecutePool {    private ExecutorService executorService;    public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {        this.executorService = new ThreadPoolExecutor(            Runtime.getRuntime().availableProcessors(),            maxPoolSize,            120L,            TimeUnit.SECONDS,            new ArrayBlockingQueue<>(queueSize)        );    }    public void execute(Runnable task) {        this.executorService.execute(task);    }}

客户端代码

客户端代码用于连接到时间服务器,发送查询时间的请求,并接收响应。以下是客户端代码的主要实现:

public class TimeClient {    public static void main(String[] args) {        Socket socket = null;        BufferedReader in = null;        PrintWriter out = null;        try {            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));            out = new PrintWriter(socket.getOutputStream(), true);            out.println("QUERY TIME ORDER");            System.out.println("send order to server succeed.");            String response = in.readLine();            System.out.println("Now is : " + response);        } catch (IOException e) {            e.printStackTrace();        } finally {            if (in != null) {                try {                    in.close();                } catch (IOException e1) {                    e1.printStackTrace();                }            }            if (out != null) {                out.close();            }            if (socket != null) {                try {                    socket.close();                } catch (IOException e1) {                    e1.printStackTrace();                }            }        }    }}

伪异步IO通信模型

伪异步IO通信模型通过线程池实现了对多个客户端请求的并发处理,避免了传统BIO模式下线程耗尽的问题。以下是通信模型的主要特点:

  • 线程池管理:服务端通过线程池(TimeServerHandlerExecutePool)管理线程资源,确保在线程数与实际并发连接数相匹配。
  • 客户端独立处理:每个客户端连接由独立的线程处理,减少了主线程的阻塞问题。
  • 灵活资源调配:线程池允许动态调整最大线程数,适应不同负载需求。

总结

伪异步IO通过线程池实现了对多个客户端请求的高效处理,相较于传统的BIO模式,能够更好地应对高并发连接。然而,线程池仍然存在一定的资源限制,无法完全消除通信线程阻塞的问题。

转载地址:http://nyux.baihongyu.com/

你可能感兴趣的文章
Mysql中存储引擎简介、修改、查询、选择
查看>>
Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
查看>>
mysql中实现rownum,对结果进行排序
查看>>
mysql中对于数据库的基本操作
查看>>
Mysql中常用函数的使用示例
查看>>
MySql中怎样使用case-when实现判断查询结果返回
查看>>
Mysql中怎样使用update更新某列的数据减去指定值
查看>>
Mysql中怎样设置指定ip远程访问连接
查看>>
mysql中数据表的基本操作很难嘛,由这个实验来带你从头走一遍
查看>>
Mysql中文乱码问题完美解决方案
查看>>
mysql中的 +号 和 CONCAT(str1,str2,...)
查看>>
Mysql中的 IFNULL 函数的详解
查看>>
mysql中的collate关键字是什么意思?
查看>>
MySql中的concat()相关函数
查看>>
mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
查看>>
MySQL中的count函数
查看>>
MySQL中的DB、DBMS、SQL
查看>>
MySQL中的DECIMAL类型:MYSQL_TYPE_DECIMAL与MYSQL_TYPE_NEWDECIMAL详解
查看>>
MySQL中的GROUP_CONCAT()函数详解与实战应用
查看>>
MySQL中的IO问题分析与优化
查看>>