基于BIO的Java Socket通信

BIO,即阻塞IO,在基于Socket的消息通信过程中,Socket服务端向外部提供服务,而Socket客户端可以建立到Socket服务端的连接,进而发送请求数据,然后等待Socket服务端处理,并返回处理结果(响应)。

基于BIO的通信,Socket服务端会发生阻塞,即在监听过程中每次accept到一个客户端的Socket连接,就要处理这个请求,而此时其他连接过来的客户端只能阻塞等待。可见,这种模式下Socket服务端的处理能力是非常有限的,客户端也只能等待,直到服务端空闲时进行请求的处理。

BIO通信实现

下面基于BIO模式,来实现一个简单的Socket服务端与Socket客户端进行通信的逻辑,对这种通信方式有一个感性的认识。具体逻辑描述如下:

1、Socket客户端连接到Socket服务端,并发送数据“I am the client N.”;

2、Socket服务端,监听服务端口,并接收客户端请求数据,如果请求数据以“I am the client”开头,则响应客户端“I am the server, and you are the Nth client.”;

Socket服务端实现,代码如下所示:

[java]  view plain  copy
  1. package org.shirdrn.<a href="http://lib.csdn.net/base/17" class='replace_word' title="Java EE知识库" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.communications.bio;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.ServerSocket;  
  7. import java.net.Socket;  
  8.   
  9. /** 
  10.  * 基于BIO的Socket服务器端 
  11.  *  
  12.  * @author shirdrn 
  13.  */  
  14. public class SimpleBioTcpServer extends Thread {  
  15.       
  16.     /** 服务端口号 */  
  17.     private int port = 8888;  
  18.     /** 为客户端分配编号  */  
  19.     private static int sequence = 0;  
  20.       
  21.     public SimpleBioTcpServer(int port) {  
  22.         this.port = port;  
  23.     }  
  24.       
  25.     @Override  
  26.     public void run() {  
  27.         Socket socket = null;  
  28.         try {  
  29.             ServerSocket serverSocket = new ServerSocket(this.port);  
  30.             while(true) {  
  31.                 socket = serverSocket.accept(); // 监听  
  32.                 this.handleMessage(socket); // 处理一个连接过来的客户端请求  
  33.             }  
  34.         } catch (IOException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  
  38.       
  39.     /** 
  40.      * 处理一个客户端socket连接 
  41.      * @param socket 客户端socket 
  42.      * @throws IOException 
  43.      */  
  44.     private void handleMessage(Socket socket) throws IOException {  
  45.         InputStream in = socket.getInputStream(); // 流:客户端->服务端(读)  
  46.         OutputStream out = socket.getOutputStream(); // 流:服务端->客户端(写)  
  47.         int receiveBytes;  
  48.         byte[] receiveBuffer = new byte[128];  
  49.         String clientMessage = "";  
  50.         if((receiveBytes=in.read(receiveBuffer))!=-1) {  
  51.             clientMessage = new String(receiveBuffer, 0, receiveBytes);  
  52.             if(clientMessage.startsWith("I am the client")) {  
  53.                 String serverResponseWords =   
  54.                     "I am the server, and you are the " + (++sequence) + "th client.";  
  55.                 out.write(serverResponseWords.getBytes());  
  56.             }  
  57.         }  
  58.         out.flush();  
  59.         System.out.println("Server: receives clientMessage->" + clientMessage);  
  60.     }  
  61.   
  62.     public static void main(String[] args) {  
  63.         SimpleBioTcpServer server = new SimpleBioTcpServer(1983);  
  64.         server.start();  
  65.     }  
  66. }  

上述实现,没有进行复杂的异常处理。

Socket客户端实现,代码如下所示:

[java]  view plain  copy
  1. package org.shirdrn.java.communications.bio;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.Socket;  
  7. import java.net.UnknownHostException;  
  8. import java.util.Date;  
  9.   
  10. /** 
  11.  * 基于BIO的Socket客户端 
  12.  *  
  13.  * @author shirdrn 
  14.  */  
  15. public class SimpleBioTcpClient {  
  16.       
  17.     private String ipAddress;  
  18.     private int port;  
  19.     private static int pos = 0;  
  20.       
  21.     public SimpleBioTcpClient() {}  
  22.       
  23.     public SimpleBioTcpClient(String ipAddress, int port) {  
  24.         this.ipAddress = ipAddress;  
  25.         this.port = port;  
  26.     }  
  27.   
  28.     /** 
  29.      * 连接Socket服务端,并模拟发送请求数据 
  30.      * @param data 请求数据 
  31.      */  
  32.     public void send(byte[] data) {  
  33.         Socket socket = null;  
  34.         OutputStream out = null;  
  35.         InputStream in = null;  
  36.         try {  
  37.             socket = new Socket(this.ipAddress, this.port); // 连接  
  38.             // 发送请求  
  39.             out = socket.getOutputStream();  
  40.             out.write(data);   
  41.             out.flush();  
  42.             // 接收响应  
  43.             in = socket.getInputStream();  
  44.             int totalBytes = 0;  
  45.             int receiveBytes = 0;  
  46.             byte[] receiveBuffer = new byte[128];  
  47.             if((receiveBytes=in.read(receiveBuffer))!=-1) {  
  48.                 totalBytes += receiveBytes;  
  49.             }  
  50.             String serverMessage = new String(receiveBuffer, 0, receiveBytes);  
  51.             System.out.println("Client: receives serverMessage->" + serverMessage);  
  52.         } catch (UnknownHostException e) {  
  53.             e.printStackTrace();  
  54.         } catch (IOException e) {  
  55.             e.printStackTrace();  
  56.         } catch (Exception e) {  
  57.             e.printStackTrace();  
  58.         } finally {  
  59.             try {  
  60.                 // 发送请求并接收到响应,通信完成,关闭连接  
  61.                 out.close();  
  62.                 in.close();  
  63.                 socket.close();  
  64.             } catch (IOException e) {  
  65.                 e.printStackTrace();  
  66.             }  
  67.         }  
  68.     }  
  69.   
  70.     public static void main(String[] args) {  
  71.         int n = 1;  
  72.         StringBuffer data = new StringBuffer();  
  73.         Date start = new Date();  
  74.         for(int i=0; i<n; i++) {  
  75.             data.delete(0, data.length());  
  76.             data.append("I am the client ").append(++pos).append(".");  
  77.             SimpleBioTcpClient client = new SimpleBioTcpClient("localhost"1983);  
  78.             client.send(data.toString().getBytes());  
  79.         }  
  80.         Date end = new Date();  
  81.         long cost = end.getTime() - start.getTime();  
  82.         System.out.println(n + " requests cost " + cost + " ms.");  
  83.     }  
  84. }  

首先启动Socket服务端进程SimpleBioTcpServer,然后再运行Socket客户端SimpleBioTcpClient。可以看到,服务端接收到请求数据,然后响应客户端,客户端接收到了服务端的响应数据。

上述实现中,对于Socket客户端和服务端都是一次写入,并一次读出,而在实际中如果每次通信过程中数据量特别大的话,服务器端是不可能接受的,可以在确定客户端请求数据字节数的情况,循环来读取并进行处理。

另外,对于上述实现中流没有进行装饰(Wrapped)处理,在实际中会有性能的损失,如不能缓冲等。

对于Socket服务端接收数据,如果可以使多次循环读取到的字节数据通过一个可变长的字节缓冲区来存储,就能方便多了,可是使用ByteArrayOutputStream,例如:

[java]  view plain  copy
  1. ByteArrayOutputStream data = new ByteArrayOutputStream();  
  2. data.write(receiveBuffer, totalBytes , totalBytes + receiveBytes);  

BIO通信测试

下面测试一下大量请求的场景下,Socket服务端处理的效率。

第一种方式:通过for循环来启动5000个Socket客户端,发送请求,代码如下所示:

[java]  view plain  copy
  1. public static void main(String[] args) {  
  2.     int n = 5000;  
  3.     StringBuffer data = new StringBuffer();  
  4.     Date start = new Date();  
  5.     for(int i=0; i<n; i++) {  
  6.         data.delete(0, data.length());  
  7.         data.append("I am the client ").append(++pos).append(".");  
  8.         SimpleBioTcpClient client = new SimpleBioTcpClient("localhost"1983);  
  9.         client.send(data.toString().getBytes());  
  10.     }  
  11.     Date end = new Date();  
  12.     long cost = end.getTime() - start.getTime();  
  13.     System.out.println(n + " requests cost " + cost + " ms.");  
  14. }  

经过测试,大约需要9864ms,大概接近10s。

第二种方式:通过启动5000个独立的客户端线程,同时请求,服务端进行计数:

[java]  view plain  copy
  1. package org.shirdrn.java.communications.bio;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.ServerSocket;  
  7. import java.net.Socket;  
  8. import java.net.UnknownHostException;  
  9. import java.util.Date;  
  10.   
  11. /** 
  12.  * 基于BIO的Socket通信测试 
  13.  *  
  14.  * @author shirdrn 
  15.  */  
  16. public class SimpleBioTcpTest {  
  17.       
  18.     static int threadCount = 5000;  
  19.       
  20.     /** 
  21.      * 基于BIO的Socket服务端进程 
  22.      *  
  23.      * @author shirdrn 
  24.      */  
  25.     static class SocketServer extends Thread {  
  26.           
  27.         /** 服务端口号 */  
  28.         private int port = 8888;  
  29.         /** 为客户端分配编号  */  
  30.         private static int sequence = 0;  
  31.           
  32.         public SocketServer(int port) {  
  33.             this.port = port;  
  34.         }  
  35.           
  36.         @Override  
  37.         public void run() {  
  38.             Socket socket = null;  
  39.             int counter = 0;  
  40.             try {  
  41.                 ServerSocket serverSocket = new ServerSocket(this.port);  
  42.                 boolean flag = false;  
  43.                 Date start = null;  
  44.                 while(true) {  
  45.                     socket = serverSocket.accept(); // 监听  
  46.                     // 有请求到来才开始计时  
  47.                     if(!flag) {  
  48.                         start = new Date();  
  49.                         flag = true;  
  50.                     }  
  51.                     this.handleMessage(socket); // 处理一个连接过来的客户端请求  
  52.                     if(++counter==threadCount) {  
  53.                         Date end = new Date();  
  54.                         long last = end.getTime() - start.getTime();  
  55.                         System.out.println(threadCount + " requests cost " + last + " ms.");  
  56.                     }  
  57.                 }  
  58.             } catch (IOException e) {  
  59.                 e.printStackTrace();  
  60.             }  
  61.         }  
  62.           
  63.         /** 
  64.          * 处理一个客户端socket连接 
  65.          * @param socket 客户端socket 
  66.          * @throws IOException 
  67.          */  
  68.         private void handleMessage(Socket socket) throws IOException {  
  69.             InputStream in = socket.getInputStream(); // 流:客户端->服务端(读)  
  70.             OutputStream out = socket.getOutputStream(); // 流:服务端->客户端(写)  
  71.             int receiveBytes;  
  72.             byte[] receiveBuffer = new byte[128];  
  73.             String clientMessage = "";  
  74.             if((receiveBytes=in.read(receiveBuffer))!=-1) {  
  75.                 clientMessage = new String(receiveBuffer, 0, receiveBytes);  
  76.                 if(clientMessage.startsWith("I am the client")) {  
  77.                     String serverResponseWords =   
  78.                         "I am the server, and you are the " + (++sequence) + "th client.";  
  79.                     out.write(serverResponseWords.getBytes());  
  80.                 }  
  81.             }  
  82.             out.flush();  
  83.             System.out.println("Server: receives clientMessage->" + clientMessage);  
  84.         }  
  85.     }  
  86.       
  87.     /** 
  88.      * 基于BIO的Socket客户端线程 
  89.      *  
  90.      * @author shirdrn 
  91.      */  
  92.     static class SocketClient implements Runnable {  
  93.           
  94.         private String ipAddress;  
  95.         private int port;  
  96.         /** 待发送的请求数据 */  
  97.         private String data;  
  98.           
  99.         public SocketClient(String ipAddress, int port) {  
  100.             this.ipAddress = ipAddress;  
  101.             this.port = port;  
  102.         }  
  103.   
  104.         @Override  
  105.         public void run() {  
  106.             this.send();              
  107.         }  
  108.           
  109.         /** 
  110.          * 连接Socket服务端,并模拟发送请求数据 
  111.          */  
  112.         public void send() {  
  113.             Socket socket = null;  
  114.             OutputStream out = null;  
  115.             InputStream in = null;  
  116.             try {  
  117.                 socket = new Socket(this.ipAddress, this.port); // 连接  
  118.                 // 发送请求  
  119.                 out = socket.getOutputStream();  
  120.                 out.write(data.getBytes());   
  121.                 out.flush();  
  122.                 // 接收响应  
  123.                 in = socket.getInputStream();  
  124.                 int totalBytes = 0;  
  125.                 int receiveBytes = 0;  
  126.                 byte[] receiveBuffer = new byte[128];  
  127.                 if((receiveBytes=in.read(receiveBuffer))!=-1) {  
  128.                     totalBytes += receiveBytes;  
  129.                 }  
  130.                 String serverMessage = new String(receiveBuffer, 0, receiveBytes);  
  131.                 System.out.println("Client: receives serverMessage->" + serverMessage);  
  132.             } catch (UnknownHostException e) {  
  133.                 e.printStackTrace();  
  134.             } catch (IOException e) {  
  135.                 e.printStackTrace();  
  136.             } catch (Exception e) {  
  137.                 e.printStackTrace();  
  138.             } finally {  
  139.                 try {  
  140.                     // 发送请求并接收到响应,通信完成,关闭连接  
  141.                     out.close();  
  142.                     in.close();  
  143.                     socket.close();  
  144.                 } catch (IOException e) {  
  145.                     e.printStackTrace();  
  146.                 }  
  147.             }  
  148.         }  
  149.   
  150.         public void setData(String data) {  
  151.             this.data = data;  
  152.         }  
  153.     }  
  154.   
  155.     public static void main(String[] args) throws Exception {  
  156.         SocketServer server = new SocketServer(1983);  
  157.         server.start();  
  158.           
  159.         Thread.sleep(3000);  
  160.           
  161.         for(int i=0; i<threadCount; i++) {  
  162.             SocketClient client = new SocketClient("localhost"1983);  
  163.             client.setData("I am the client " + (i+1) + ".");  
  164.             new Thread(client).start();  
  165.             Thread.sleep(01);  
  166.         }         
  167.     }  
  168. }  

经过测试,大约需要7110ms,大概接近7s,没有太大提高。

BIO通信改进

通过上面的测试我们可以发现,在Socket服务端对来自客户端的请求进行处理时,会发生阻塞,严重地影响了能够并发处理请求的效率。实际上,在Socket服务端接收来自客户端连接能力的范围内,可以将接收请求独立出来,从而在将处理请求独立粗话来,通过一个请求一个线程处理的方式来解决上述问题。这样,服务端是多处理线程对应客户端多请求,处理效率有一定程度的提高。

下面,通过单线程接收请求,然后委派线程池进行多线程并发处理请求:

[java]  view plain  copy
  1. /** 
  2.      * 基于BIO的Socket服务端进程 
  3.      *  
  4.      * @author shirdrn 
  5.      */  
  6.     static class SocketServer extends Thread {  
  7.           
  8.         /** 服务端口号 */  
  9.         private int port = 8888;  
  10.         /** 为客户端分配编号  */  
  11.         private static int sequence = 0;  
  12.         /** 处理客户端请求的线程池 */  
  13.         private ExecutorService pool;  
  14.           
  15.         public SocketServer(int port, int poolSize) {  
  16.             this.port = port;  
  17.             this.pool = Executors.newFixedThreadPool(poolSize);  
  18.         }  
  19.           
  20.         @Override  
  21.         public void run() {  
  22.             Socket socket = null;  
  23.             int counter = 0;  
  24.             try {  
  25.                 ServerSocket serverSocket = new ServerSocket(this.port);  
  26.                 boolean flag = false;  
  27.                 Date start = null;  
  28.                 while(true) {  
  29.                     socket = serverSocket.accept(); // 监听  
  30.                     // 有请求到来才开始计时  
  31.                     if(!flag) {  
  32.                         start = new Date();  
  33.                         flag = true;  
  34.                     }  
  35.                     // 将客户端请求放入线程池处理  
  36.                     pool.execute(new RequestHandler(socket));  
  37.                     if(++counter==threadCount) {  
  38.                         Date end = new Date();  
  39.                         long last = end.getTime() - start.getTime();  
  40.                         System.out.println(threadCount + " requests cost " + last + " ms.");  
  41.                     }  
  42.                 }  
  43.             } catch (IOException e) {  
  44.                 e.printStackTrace();  
  45.             }  
  46.         }  
  47.           
  48.         /** 
  49.          * 客户端请求处理线程类 
  50.          *  
  51.          * @author shirdrn 
  52.          */  
  53.         class RequestHandler implements Runnable {  
  54.   
  55.             private Socket socket;  
  56.               
  57.             public RequestHandler(Socket socket) {  
  58.                 this.socket = socket;  
  59.             }  
  60.               
  61.             @Override  
  62.             public void run() {  
  63.                 try {  
  64.                     InputStream in = socket.getInputStream(); // 流:客户端->服务端(读)  
  65.                     OutputStream out = socket.getOutputStream(); // 流:服务端->客户端(写)  
  66.                     int receiveBytes;  
  67.                     byte[] receiveBuffer = new byte[128];  
  68.                     String clientMessage = "";  
  69.                     if((receiveBytes=in.read(receiveBuffer))!=-1) {  
  70.                         clientMessage = new String(receiveBuffer, 0, receiveBytes);  
  71.                         if(clientMessage.startsWith("I am the client")) {  
  72.                             String serverResponseWords =   
  73.                                 "I am the server, and you are the " + (++sequence) + "th client.";  
  74.                             out.write(serverResponseWords.getBytes());  
  75.                         }  
  76.                     }  
  77.                     out.flush();  
  78.                     System.out.println("Server: receives clientMessage->" + clientMessage);  
  79.                 } catch (IOException e) {  
  80.                     e.printStackTrace();  
  81.                 }                 
  82.             }  
  83.         }  
  84.     }  

可见,这种改进方式增强服务端处理请求的并发度,但是每一个请求都要由一个线程去处理,大量请求造成服务端启动大量进程进行处理,也是比较占用服务端资源的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值