分享

非阻塞通信

 windli笔记 2011-09-15
对于用ServerSocket和Socket写的服务器程序或着客户端程序,在运行的时候常常会阻塞,如当一个线程执行ServerSocket的accept()方法,如果没有客户机连接,该线程就会一直阻塞直到有了客户机连接才从accept()方法返回,再如,当线程执行Socket的read()方法,如果输入流中没有数据,该线程就会一直等到有数据可读时才从read()方法返回。

    如果服务器要与多个客户机通信,通常做法为每个客户机连接开启一个服务线程,每个工作线程都有可能经常处于长时间的阻塞状态。

    从JDK1.4版本开始,引入了非阻塞的通信机制。服务器程序接收客户连接、客户程序建立与服务器的连接,以及服务器程序和客户程序收发数据的操作都可以按非阻塞的方式进行。服务器程序只需要创建一个线程,就能完成同时与多个客户通信的任务。

    非阻塞通信要比传统的阻塞方式效率要高,Apache的MIMA框架就是以java.nio包中的类编写的。

    不知道是否有朋友看过 孙卫琴写的《Java网络编程精解》,在提到线程阻塞的时

Java网络编程精解 第84页 写道
线程从Socket的输入流读入数据时,如果没有足够的数据,就会进入阻塞状态,直到读到了足够的数据,或者到达输入流的未尾,或者出现了异常,才从输入流的read()方法返回或异常中断。输入流中有多少数据才算足够呢,这要看线程执行read方法的类型。
    int read():只要输入有一个字节,就算足够。
    int read(byte[] buff):只要输入流中的字节数目与参数buff数组的长度相同,就算足够。

 我对描红的描述持不同的意见

  byte[] msgBytes = new byte[512];
  inputStream.read(msgBytes); 

如果按书中描述,这行代码必须读到512个字节后才从阻塞状态中返回,如果没有读到足够的512个字节,则一直阻塞。但实际情况却不是这样的,只要流里哪怕只有一个字节 ,inputStream.read(msgBytes)也会立即返回,返回值为读到的字节数。

下面是简单的NIO示例

1、服务端程序,非阻塞方式

Java代码 复制代码 收藏代码
  1. package com.bill99.nioserver;   
  2.   
  3. import java.io.IOException;   
  4. import java.net.InetSocketAddress;   
  5. import java.nio.ByteBuffer;   
  6. import java.nio.channels.SelectionKey;   
  7. import java.nio.channels.Selector;   
  8. import java.nio.channels.ServerSocketChannel;   
  9. import java.nio.channels.SocketChannel;   
  10. import java.nio.channels.spi.SelectorProvider;   
  11. import java.nio.charset.Charset;   
  12. import java.util.Iterator;   
  13.   
  14. public class NIOServer {   
  15.     private Selector socketSelector = null;   
  16.     private ServerSocketChannel ssChannel = null;   
  17.     private SocketChannel socketChannel =null;   
  18.     private static SelectionKey key = null;   
  19.     private int port =5512;   
  20.     private int backlog = 100;   
  21.     private Charset charset = Charset.defaultCharset();   
  22.     private ByteBuffer shareBuffer = ByteBuffer.allocate(1024);//生成1kb的缓冲区,可以根据实际情况调的更大些   
  23.        
  24.     public NIOServer()  {   
  25.         try {   
  26.             socketSelector = SelectorProvider.provider().openSelector();   
  27.             ssChannel =ServerSocketChannel.open() ;   
  28.             ssChannel.socket().bind(new InetSocketAddress(port),100);   
  29.             System.out.println(String.format("NIO服务器启动,监听端口%1$s,最大连接数%2$s", port,backlog));   
  30.         } catch(IOException e){   
  31.             throw new ExceptionInInitializerError(e);   
  32.         }   
  33.     }   
  34.     /**  
  35.      * 接收客户端连接  
  36.      */  
  37.     public void acceptConnect() {   
  38.         while(true) {   
  39.             try {   
  40.                 SocketChannel socketChannel = ssChannel.accept();//阻塞模式,直到有连接进入   
  41.                 System.out.println("收到客户机连接,来自:"+ssChannel.socket().getInetAddress());   
  42.                 socketChannel.configureBlocking(false);//设置非阻塞模式   
  43.                 synchronized(this){   
  44.                     socketSelector.wakeup();   
  45.                     socketChannel.register(socketSelector,SelectionKey.OP_READ|   
  46.                                                           SelectionKey.OP_WRITE);   
  47.                 }   
  48.             } catch(IOException e){e.printStackTrace();}   
  49.         }   
  50.     }   
  51.     /**  
  52.      * 读写服务  
  53.      * @throws IOException  
  54.      */  
  55.     public void service() throws IOException{   
  56.         while (true) {   
  57.             synchronized (this) {//空的同步块,目的是为了避免死锁   
  58.             }   
  59.             if (!(socketSelector.select() > 0)) {   
  60.                 continue;   
  61.             }   
  62.             Iterator<SelectionKey> it = socketSelector.selectedKeys().iterator();   
  63.             while (it.hasNext()) {   
  64.                 key = it.next();   
  65.                 it.remove();   
  66.                 if(key.isReadable()) {// 读就绪   
  67.                     this.readDataFromSocket(key);   
  68.                 }   
  69.                 if(key.isWritable()){//写就绪   
  70.                     this.sayWelcome(key);   
  71.                 }   
  72.             }   
  73.         }   
  74.     }   
  75.     //读取客户机发来的数据   
  76.     private void readDataFromSocket(SelectionKey key) throws IOException {   
  77.         shareBuffer.clear();//清空buffer   
  78.         socketChannel=(SocketChannel) key.channel();   
  79.         int num=0;   
  80.         while((num = socketChannel.read(shareBuffer))>0){   
  81.             shareBuffer.flip();//将当前极限设置为位置,并把设置后的位置改为0   
  82.         }   
  83.         if(num ==-1){//读取流的未尾,对方已关闭流   
  84.             socketChannel.close();   
  85.             return;   
  86.         }   
  87.         System.out.println("client request:"+charset.decode(shareBuffer).toString());   
  88.     }    
  89.     //向客户机发响应信息   
  90.     private void sayWelcome(SelectionKey key) throws IOException {   
  91.         shareBuffer.clear();//清空buffer   
  92.         socketChannel=(SocketChannel) key.channel();   
  93.         shareBuffer.put("Welcome to china!this is a greate and very beautifual country!\n".getBytes());   
  94.         shareBuffer.flip();//将当前极限设置为位置,并把设置后的位置改为0   
  95.         socketChannel.write(shareBuffer);   
  96.     }   
  97.     //Main方法   
  98.     public static void main(String[] args) {   
  99.         final NIOServer server = new NIOServer();   
  100.         Runnable task = new  Runnable() {   
  101.             public void run() {   
  102.                 server.acceptConnect();   
  103.             }   
  104.         };   
  105.         new Thread(task).start();//启动处理客户机连接的线程   
  106.         try {   
  107.             server.service();   
  108.         } catch (IOException e) {//发生IO流异常时,关闭对应的socket   
  109.             try {   
  110.                 key.channel().close();   
  111.                 key.cancel();   
  112.             } catch (IOException e1) {   
  113.                 e1.printStackTrace();   
  114.             }   
  115.         }   
  116.     }   
  117. }  

 2、客户端程序,阻塞方式

Java代码 复制代码 收藏代码
  1. package com.bill99.client;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.InputStream;   
  5. import java.io.OutputStream;   
  6. import java.net.Socket;   
  7. import java.nio.CharBuffer;   
  8.   
  9. import javax.net.SocketFactory;   
  10. //测试类   
  11. public class BlockingClient {   
  12.     private Socket socket = null;   
  13.     private OutputStream out = null;   
  14.     private InputStream in = null;   
  15.        
  16.     public BlockingClient() {   
  17.         try {   
  18.             socket= SocketFactory.getDefault().createSocket("127.0.0.1"5512);   
  19.             out = socket.getOutputStream();   
  20.             in = socket.getInputStream();   
  21.         } catch (IOException e) {   
  22.             e.printStackTrace();   
  23.         }   
  24.     }   
  25.     //发送请求并接收应答   
  26.     public String receiveRespMsg(String reqMsg) throws IOException{   
  27.         out.write(reqMsg.getBytes());   
  28.         out.flush();   
  29.         in = socket.getInputStream();   
  30.         int c =0;   
  31.         CharBuffer buffer = CharBuffer.allocate(1024);   
  32.         while((c=in.read())!=-1 && c!=10){   
  33.             buffer.put((char)c);   
  34.         }   
  35.         return new String(buffer.array()).trim();   
  36.     }   
  37.        
  38.     public static void main(String[] args) throws Exception{   
  39.         BlockingClient client = new BlockingClient();   
  40.         System.out.println("服务器响应:"+client.receiveRespMsg("hello\n"));   
  41.     }   
  42. }  

 

    总体而信,阻塞模式和非阻塞模式都可以同时处理多个客户机的连接,但阻塞模式需要较多的线程许多时间都浪费在阻塞I/O操作上,Java虚拟机需要频繁地转让CPU的使用权,而非阻塞模式只需要少量线程即可完成所有任务,非阻塞模式能更有效的利用CPU,系统开销小,能够提高程序的并发性能。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多