解读NIO Socket非阻塞模式

3 篇文章 0 订阅

前言:
     jdk供的无阻塞I/O(NIO)有效解决了多线程服务器存在的线程开销问题,但在使用上略显得复杂一些。在NIO中使用多线程,主要目的已不是为了应对 每个客户端请求而分配独立的服务线程,而是通过多线程充分使用用多个CPU的处理能力和处理中的等待时间,达到提高服务能力的目的。
    这段时间在研究NIO,写篇博客来记住学过的东西。还是从最简单的Hello World开始,
client多线程请求server端,server接收client的名字,并返回Hello! +名字的字符格式给client。当然实际应用并不这么简单,实际可能是访问文件或者数据库获取信息返回给client。非阻塞的NIO有何神秘之处?代码:

1)server端代码

Java代码
  1. /**  
  2.  *   
  3.  * @author Jeff  
  4.  *  
  5.  */   
  6. public   class  HelloWorldServer {  
  7.   
  8.     static   int  BLOCK =  1024 ;  
  9.     static  String name =  "" ;  
  10.     protected  Selector selector;  
  11.     protected  ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);  
  12.     protected  CharsetDecoder decoder;  
  13.     static  CharsetEncoder encoder = Charset.forName( "GB2312" ).newEncoder();  
  14.   
  15.     public  HelloWorldServer( int  port)  throws  IOException {  
  16.         selector = this .getSelector(port);  
  17.         Charset charset = Charset.forName("GB2312" );  
  18.         decoder = charset.newDecoder();  
  19.     }  
  20.   
  21.     // 获取Selector   
  22.     protected  Selector getSelector( int  port)  throws  IOException {  
  23.         ServerSocketChannel server = ServerSocketChannel.open();  
  24.         Selector sel = Selector.open();  
  25.         server.socket().bind(new  InetSocketAddress(port));  
  26.         server.configureBlocking(false );  
  27.         server.register(sel, SelectionKey.OP_ACCEPT);  
  28.         return  sel;  
  29.     }  
  30.   
  31.     // 监听端口   
  32.     public   void  listen() {  
  33.         try  {  
  34.             for  (;;) {  
  35.                 selector.select();  
  36.                 Iterator iter = selector.selectedKeys().iterator();  
  37.                 while  (iter.hasNext()) {  
  38.                     SelectionKey key = (SelectionKey) iter.next();  
  39.                     iter.remove();  
  40.                     process(key);  
  41.                 }  
  42.             }  
  43.         } catch  (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47.   
  48.     // 处理事件   
  49.     protected   void  process(SelectionKey key)  throws  IOException {  
  50.         if  (key.isAcceptable()) {  // 接收请求   
  51.             ServerSocketChannel server = (ServerSocketChannel) key.channel();  
  52.             SocketChannel channel = server.accept();  
  53.             //设置非阻塞模式   
  54.             channel.configureBlocking(false );  
  55.             channel.register(selector, SelectionKey.OP_READ);  
  56.         } else   if  (key.isReadable()) {  // 读信息   
  57.             SocketChannel channel = (SocketChannel) key.channel();  
  58.             int  count = channel.read(clientBuffer);  
  59.             if  (count >  0 ) {  
  60.                 clientBuffer.flip();  
  61.                 CharBuffer charBuffer = decoder.decode(clientBuffer);  
  62.                 name = charBuffer.toString();  
  63.                 // System.out.println(name);   
  64.                 SelectionKey sKey = channel.register(selector,  
  65.                         SelectionKey.OP_WRITE);  
  66.                 sKey.attach(name);  
  67.             } else  {  
  68.                 channel.close();  
  69.             }  
  70.   
  71.             clientBuffer.clear();  
  72.         } else   if  (key.isWritable()) {  // 写事件   
  73.             SocketChannel channel = (SocketChannel) key.channel();  
  74.             String name = (String) key.attachment();  
  75.               
  76.             ByteBuffer block = encoder.encode(CharBuffer  
  77.                     .wrap("Hello !"  + name));  
  78.               
  79.   
  80.             channel.write(block);  
  81.   
  82.             //channel.close();   
  83.   
  84.         }  
  85.     }  
  86.   
  87.     public   static   void  main(String[] args) {  
  88.         int  port =  8888 ;  
  89.         try  {  
  90.             HelloWorldServer server = new  HelloWorldServer(port);  
  91.             System.out.println("listening on "  + port);  
  92.               
  93.             server.listen();  
  94.               
  95.         } catch  (IOException e) {  
  96.             e.printStackTrace();  
  97.         }  
  98.     }  
  99. }  
/**
 * 
 * @author Jeff
 *
 */
public class HelloWorldServer {

	static int BLOCK = 1024;
	static String name = "";
	protected Selector selector;
	protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
	protected CharsetDecoder decoder;
	static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();

	public HelloWorldServer(int port) throws IOException {
		selector = this.getSelector(port);
		Charset charset = Charset.forName("GB2312");
		decoder = charset.newDecoder();
	}

	// 获取Selector
	protected Selector getSelector(int port) throws IOException {
		ServerSocketChannel server = ServerSocketChannel.open();
		Selector sel = Selector.open();
		server.socket().bind(new InetSocketAddress(port));
		server.configureBlocking(false);
		server.register(sel, SelectionKey.OP_ACCEPT);
		return sel;
	}

	// 监听端口
	public void listen() {
		try {
			for (;;) {
				selector.select();
				Iterator iter = selector.selectedKeys().iterator();
				while (iter.hasNext()) {
					SelectionKey key = (SelectionKey) iter.next();
					iter.remove();
					process(key);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 处理事件
	protected void process(SelectionKey key) throws IOException {
		if (key.isAcceptable()) { // 接收请求
			ServerSocketChannel server = (ServerSocketChannel) key.channel();
			SocketChannel channel = server.accept();
			//设置非阻塞模式
			channel.configureBlocking(false);
			channel.register(selector, SelectionKey.OP_READ);
		} else if (key.isReadable()) { // 读信息
			SocketChannel channel = (SocketChannel) key.channel();
			int count = channel.read(clientBuffer);
			if (count > 0) {
				clientBuffer.flip();
				CharBuffer charBuffer = decoder.decode(clientBuffer);
				name = charBuffer.toString();
				// System.out.println(name);
				SelectionKey sKey = channel.register(selector,
						SelectionKey.OP_WRITE);
				sKey.attach(name);
			} else {
				channel.close();
			}

			clientBuffer.clear();
		} else if (key.isWritable()) { // 写事件
			SocketChannel channel = (SocketChannel) key.channel();
			String name = (String) key.attachment();
			
			ByteBuffer block = encoder.encode(CharBuffer
					.wrap("Hello !" + name));
			

			channel.write(block);

			//channel.close();

		}
	}

	public static void main(String[] args) {
		int port = 8888;
		try {
			HelloWorldServer server = new HelloWorldServer(port);
			System.out.println("listening on " + port);
			
			server.listen();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


server主要是读取client发过来的信息,并返回一条信息

2)client端代码

Java代码
  1. /**  
  2.  *   
  3.  * @author Jeff  
  4.  *  
  5.  */   
  6. public   class  HelloWorldClient {  
  7.   
  8.     static   int  SIZE =  10 ;  
  9.     static  InetSocketAddress ip =  new  InetSocketAddress( "localhost"8888 );  
  10.     static  CharsetEncoder encoder = Charset.forName( "GB2312" ).newEncoder();  
  11.   
  12.     static   class  Message  implements  Runnable {  
  13.         protected  String name;  
  14.         String msg = "" ;  
  15.   
  16.         public  Message(String index) {  
  17.             this .name = index;  
  18.         }  
  19.   
  20.         public   void  run() {  
  21.             try  {  
  22.                 long  start = System.currentTimeMillis();  
  23.                 //打开Socket通道   
  24.                 SocketChannel client = SocketChannel.open();  
  25.                 //设置为非阻塞模式   
  26.                 client.configureBlocking(false );  
  27.                 //打开选择器   
  28.                 Selector selector = Selector.open();  
  29.                 //注册连接服务端socket动作   
  30.                 client.register(selector, SelectionKey.OP_CONNECT);  
  31.                 //连接   
  32.                 client.connect(ip);  
  33.                 //分配内存   
  34.                 ByteBuffer buffer = ByteBuffer.allocate(8  *  1024 );  
  35.                 int  total =  0 ;  
  36.   
  37.                 _FOR: for  (;;) {  
  38.                     selector.select();  
  39.                     Iterator iter = selector.selectedKeys().iterator();  
  40.   
  41.                     while  (iter.hasNext()) {  
  42.                         SelectionKey key = (SelectionKey) iter.next();  
  43.                         iter.remove();  
  44.                         if  (key.isConnectable()) {  
  45.                             SocketChannel channel = (SocketChannel) key  
  46.                                     .channel();  
  47.                             if  (channel.isConnectionPending())  
  48.                                 channel.finishConnect();  
  49.                             channel  
  50.                                     .write(encoder  
  51.                                             .encode(CharBuffer.wrap(name)));  
  52.   
  53.                             channel.register(selector, SelectionKey.OP_READ);  
  54.                         } else   if  (key.isReadable()) {  
  55.                             SocketChannel channel = (SocketChannel) key  
  56.                                     .channel();  
  57.                             int  count = channel.read(buffer);  
  58.                             if  (count >  0 ) {  
  59.                                 total += count;  
  60.                                 buffer.flip();  
  61.   
  62.                                 while  (buffer.remaining() >  0 ) {  
  63.                                     byte  b = buffer.get();  
  64.                                     msg += (char ) b;  
  65.                                       
  66.                                 }  
  67.   
  68.                                 buffer.clear();  
  69.                             } else  {  
  70.                                 client.close();  
  71.                                 break  _FOR;  
  72.                             }  
  73.                         }  
  74.                     }  
  75.                 }  
  76.                 double  last = (System.currentTimeMillis() - start) *  1.0  /  1000 ;  
  77.                 System.out.println(msg + "used time :"  + last +  "s." );  
  78.                 msg = "" ;  
  79.             } catch  (IOException e) {  
  80.                 e.printStackTrace();  
  81.             }  
  82.         }  
  83.     }  
  84.   
  85.     public   static   void  main(String[] args)  throws  IOException {  
  86.       
  87.         String names[] = new  String[SIZE];  
  88.   
  89.         for  ( int  index =  0 ; index < SIZE; index++) {  
  90.             names[index] = "jeff["  + index +  "]" ;  
  91.             new  Thread( new  Message(names[index])).start();  
  92.         }  
  93.       
  94.     }  
  95. }  
/**
 * 
 * @author Jeff
 *
 */
public class HelloWorldClient {

	static int SIZE = 10;
	static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);
	static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();

	static class Message implements Runnable {
		protected String name;
		String msg = "";

		public Message(String index) {
			this.name = index;
		}

		public void run() {
			try {
				long start = System.currentTimeMillis();
				//打开Socket通道
				SocketChannel client = SocketChannel.open();
				//设置为非阻塞模式
				client.configureBlocking(false);
				//打开选择器
				Selector selector = Selector.open();
				//注册连接服务端socket动作
				client.register(selector, SelectionKey.OP_CONNECT);
				//连接
				client.connect(ip);
				//分配内存
				ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
				int total = 0;

				_FOR: for (;;) {
					selector.select();
					Iterator iter = selector.selectedKeys().iterator();

					while (iter.hasNext()) {
						SelectionKey key = (SelectionKey) iter.next();
						iter.remove();
						if (key.isConnectable()) {
							SocketChannel channel = (SocketChannel) key
									.channel();
							if (channel.isConnectionPending())
								channel.finishConnect();
							channel
									.write(encoder
											.encode(CharBuffer.wrap(name)));

							channel.register(selector, SelectionKey.OP_READ);
						} else if (key.isReadable()) {
							SocketChannel channel = (SocketChannel) key
									.channel();
							int count = channel.read(buffer);
							if (count > 0) {
								total += count;
								buffer.flip();

								while (buffer.remaining() > 0) {
									byte b = buffer.get();
									msg += (char) b;
									
								}

								buffer.clear();
							} else {
								client.close();
								break _FOR;
							}
						}
					}
				}
				double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
				System.out.println(msg + "used time :" + last + "s.");
				msg = "";
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
	
		String names[] = new String[SIZE];

		for (int index = 0; index < SIZE; index++) {
			names[index] = "jeff[" + index + "]";
			new Thread(new Message(names[index])).start();
		}
	
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值