博客
关于我
一个简单的伪异步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/

你可能感兴趣的文章
Python中使用PIL快速实现二值图
查看>>
Python中使用PIL快速实现灰度图
查看>>
Python中使用pip install ncmbot时各种错误解决办法
查看>>
Python中使用requests和parsel爬取喜马拉雅电台音频
查看>>
Python中使用turtle绘制多个同心圆
查看>>
Python中使用turtle绘制棋盘详解
查看>>
Python中使用wordcloud生成漂亮的中文词云
查看>>
Python中使用wxpy定时机器人给微信好友发送每日一文
查看>>
Python中使用zip()并行迭代
查看>>
Python中使用推导式创建序列
查看>>
Python中信号处理程序和atexit处理程序的调用
查看>>
Python中关于txt的简单读写模式与操作
查看>>
Python中关于类和函数的初体验之"__init__"和"__str__"不是"_init_"和"_str_"
查看>>
python中函数接受参数为*args, **kwargs怎么办
查看>>
Python中切片的高效迭代
查看>>
python中列表乘法、eval、lambda、hasattr、assert、*(星)等的用法
查看>>
Python中制作词云的WordCloud参数详解
查看>>
Python中可用和使用的系统内存?
查看>>
python中存根文件(.pyi)的用途是什么?
查看>>
Python中实现ASCII码与字符相互转换
查看>>