NIO编程

 传统的BIO(blocking I/O)是阻塞的,服务器端:ServerSocket负责绑定IP地址,启动监听端口,然后一直等待着客户端连接,是阻塞的状态;客户端:Socket负责发起连接操作。连接成功后,读和写的操作同样是等待阻塞的。经典模型是来一个客户端,起一个线程,因为主线程要负责监听,要重起一条线程处理客户端请求。

NIO (non-blocking I/O)是同步非阻塞。打个比方,客户端请求服务器端建立连接,就好像服务器端有很多个插孔,等着客户端来插。NIO有一个大管家selecter一直在轮询处理客户端的连接和读写请求,先在那些插孔上放(register)一些key(对应编程api里SelectionKey.OP_ACCEPT),看看有没有人来连接,如果有则连接。连接之后再连接的通道上放上读写的key(下面的程序是SelectionKey.OP_READ)

package com.java.yan;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NioSocketDemo {
	private Selector selector;
	public void initServer(int port) throws IOException{
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		serverChannel.socket().bind(new InetSocketAddress(port));
		
		this.selector = Selector.open();
		serverChannel.register(selector,SelectionKey.OP_ACCEPT);
		System.out.println("服务器已启动。。。");
	}
	public void listenSelector() throws IOException{
		while(true){
			this.selector.select();
			Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
			while(it.hasNext()){
				SelectionKey key = it.next();
				it.remove();
				handler(key);
			}
		}
	}
	private void handler(SelectionKey key) throws IOException {
		if(key.isAcceptable()){
			ServerSocketChannel serverchannel = (ServerSocketChannel) key.channel();
			SocketChannel socketChannel = serverchannel.accept();
			socketChannel.configureBlocking(false);
			socketChannel.register(selector, SelectionKey.OP_READ);
		}else if(key.isReadable()){
			SocketChannel socketChannel = (SocketChannel)key.channel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			int readData = socketChannel.read(buffer);
			if(readData > 0){
				String info = new String(buffer.array(),"GBK").trim();
				System.out.println("服务端收到数据:"+info);
			}else{
				System.out.println("客户端关闭。。。。");
				key.cancel();
			}
		}
	}
	public static void main(String[] args) throws IOException {
		NioSocketDemo niodemo = new NioSocketDemo();
		niodemo.initServer(8888);
		niodemo.listenSelector();
	}

}

上面的是单线程模式的NIO,还有升级版的,一个selector负责轮询,但是只处理客户端连接,连接成功会有对应线程处理读写工作,引入线程池。

  AIO(Asynchronous I/O) 是异步非阻塞,先前是selector主动轮询,现在换成客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理。

等待完善。。。。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值