首页 > 其他 > 详细

Bio Nio Aio demo

时间:2020-09-15 17:09:51      阅读:54      评论:0      收藏:0      [点我收藏+]

BIO:

 1 public class BioServer {
 2 
 3 
 4     @SuppressWarnings("all")
 5     public static void main(String[] args) throws IOException {
 6 
 7         ServerSocket serverSocket = new ServerSocket(8000);
 8 
 9         new Thread(() -> {
10             try {
11                 Socket socket = serverSocket.accept();
12 
13                 new Thread(() -> {
14                     byte[] data = new byte[1024];
15                     try {
16                         InputStream inputStream = socket.getInputStream();
17                         while (true) {
18                             int len;
19                             while ((len = inputStream.read(data)) != -1) {
20                                 System.out.println(new String(data, 0, len));
21                             }
22                         }
23                     } catch (IOException e) {
24                         e.printStackTrace();
25                     }
26                 }).start();
27             } catch (IOException e) {
28                 e.printStackTrace();
29             }
30         }).start();
31 
32     }
33 
34 
35 }
 1 public class BioClient {
 2 
 3 
 4     @SuppressWarnings("all")
 5     public static void main(String[] args) {
 6 
 7         new Thread(() -> {
 8             try {
 9                 Socket socket = new Socket("127.0.0.1", 8000);
10                 while (true) {
11                     socket.getOutputStream().write((new Date() + ": hello world ").getBytes());
12                     socket.getOutputStream().flush();
13                     Thread.sleep(2000);
14                 }
15             } catch (IOException | InterruptedException e) {
16                 e.printStackTrace();
17             }
18         }).start();
19 
20 
21     }
22 }

result: 

Tue Sep 15 14:54:19 CST 2020: hello world
Tue Sep 15 14:54:21 CST 2020: hello world
Tue Sep 15 14:54:23 CST 2020: hello world
Tue Sep 15 14:54:25 CST 2020: hello world
Tue Sep 15 14:54:27 CST 2020: hello world
Tue Sep 15 14:54:29 CST 2020: hello world
Tue Sep 15 14:54:31 CST 2020: hello world
Tue Sep 15 14:54:33 CST 2020: hello world

Bio Nio Aio demo

原文:https://www.cnblogs.com/enchaolee/p/13673166.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!