关于NIO的理解及相关的例子

本文详细介绍了NIO服务端与客户端的工作原理及实现方式,包括如何建立非阻塞通道、注册事件、处理客户端连接及消息交互等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

NIO一般有服务端和客户端组成,服务端轮询等待客户端的连接,但为非阻塞。例子如下
服务端:
/**
 * NIO服务端
 * @author 734621
  *1. 学校(ServerSocketChannel) 
  *2. 学校教务处(Selector) 
  *3. 老师 (ServerSocket ) 
  *4. 学生 (SocketChannel) 
  *5. 员工号/学生号(SelectionKey) 
 */
public class NIOServer {
	//通道管理器 
   private Selector selector;
   
   /** 
    * 获得一个ServerSocket通道,并对该通道做一些初始化的工作 
    * @param port  绑定的端口号 
    * @throws IOException 
    */  
   public void initServer(int port) throws IOException{
	  // 获得一个ServerSocket通道  创建学校
	   ServerSocketChannel serverChannel = ServerSocketChannel.open();
	   // 设置通道为非阻塞 
	   serverChannel.configureBlocking(false);
	   // 将该通道对应的ServerSocket绑定到port端口  
	   serverChannel.socket().bind(new InetSocketAddress(port));
	   // 获得一个通道管理器  创立教务处
	   this.selector = Selector.open();
	   
	   //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,  
       //当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。  
	   // 把教务处绑定到学校
	   serverChannel.register(selector, SelectionKey.OP_ACCEPT);
	   
   }
   
   /** 
    * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 
    * @throws IOException 
    */ 
   public void listen() throws IOException{
	   System.out.println("服务端启动成功!");  
       // 轮询访问selector  开学了,等待学生来报道和问问题
	   while(true){
		 //当注册的事件到达时,方法返回;否则,该方法会一直阻塞   
		  int selectCount = selector.select();
		    if(selectCount <1)
		    	continue;//没有学生来报道或者问问题
		// 获得selector中选中的项的迭代器,选中的项为注册的事件   
		    /**
		     * 教务处保存了老师的工号和学生的学号  把工号和学号拿出来,
		     * 如果是老师的工号,则认为老师带学生来报道
		     * 如果是学生的学号,则认为是学生来问问题
		     */
		   Set<SelectionKey> keys = selector.selectedKeys();
		   Iterator ite = keys.iterator();
		   while(ite.hasNext()){
			   //获得老师的工号或者学生的学号
			   SelectionKey key = (SelectionKey)ite.next();
			   //删除已选的key,以防重复处理  
			   ite.remove();
			   // 客户端请求连接事件   获得老师工号,即带学生报名
			   if(key.isAcceptable()){
				   //找到老师所在的学校
				   ServerSocketChannel server = (ServerSocketChannel) key.channel();
					// 获得和客户端连接的通道  学生报名成功 
					  SocketChannel channel = server.accept();
					  
					// 设置成非阻塞  
					  channel.configureBlocking(false);
					   
					//在这里可以给客户端发送信息哦  
					//学生可以问问题了
					 channel.write(ByteBuffer.wrap("来自服务端的消息,".getBytes()));
					//在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。 
					 //注册学号成功,并分配学生的权限 
					 channel.register(selector, SelectionKey.OP_READ);
			   }else if(key.isReadable()){//学生来问问题  很明显,这是这学生,因为所有带OP_READ的人都是前面由招生办老师带过来注册过的。
				   read(key);
				   
			   }
		   }
	   }
   }
   
   public void read(SelectionKey key) throws IOException{
	   // 服务器可读取消息:得到事件发生的Socket通道  
	   //通过学号知道是谁问的问题 
	   SocketChannel channel = (SocketChannel) key.channel();
	   // 创建读取的缓冲区  
	   ByteBuffer byteBuffer = ByteBuffer.allocate(100);
	   //学生问问题
	   channel.read(byteBuffer);
	  
	   byte[] data = byteBuffer.array();
	   
	   String msg = new String(data).trim();
	   
	   System.out.println("服务端接收到的消息:"+msg);
	   ByteBuffer msgBuffer = ByteBuffer.wrap(msg.getBytes());
	   
	   channel.write(msgBuffer);
	   
   }
   
   public static void main(String [] args) throws IOException{
	  
	   NIOServer server = new NIOServer();
	   server.initServer(8000);;
	   server.listen();
   }
}

客户端:

/**
 * NIO客户端 
 * @author 734621
 *
 */
public class NIOClient {

	private Selector selector;
	
	 /** 
     * 获得一个Socket通道,并对该通道做一些初始化的工作 
     * @param ip 连接的服务器的ip 
     * @param port  连接的服务器的端口号          
     * @throws IOException 
     */  
	public void initClient(String ip,int port) throws IOException{
		//获得一个Socket通道  
		SocketChannel channel = SocketChannel.open();
		// 设置通道为非阻塞  
		channel.configureBlocking(false);
        // 获得一个通道管理器 
		this.selector = Selector.open();
		 // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调  
        //用channel.finishConnect();才能完成连接  
		channel.connect(new InetSocketAddress(ip,port));
		
		//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。  
		channel.register(selector, SelectionKey.OP_CONNECT);
		
	}
	/** 
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 
     * @throws IOException 
     */  
	public void listen() throws IOException{
		// 轮询访问selector  
        while (true) {  
            selector.select();  
            // 获得selector中选中的项的迭代器  
            Iterator ite = this.selector.selectedKeys().iterator();  
            while (ite.hasNext()) {  
                SelectionKey key = (SelectionKey) ite.next();  
                // 删除已选的key,以防重复处理  
                ite.remove();  
                // 连接事件发生  
                if (key.isConnectable()) {  
                    SocketChannel channel = (SocketChannel) key  
                            .channel();  
                    // 如果正在连接,则完成连接  
                    if(channel.isConnectionPending()){  
                        channel.finishConnect();  
                          
                    }  
                    // 设置成非阻塞  
                    channel.configureBlocking(false);  
  
                    //在这里可以给服务端发送信息哦  
                    channel.write(ByteBuffer.wrap(new String("这是来自客户端的一条信息,").getBytes()));  
                    //在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。  
                    channel.register(this.selector, SelectionKey.OP_READ);  
                      
                    // 获得了可读的事件  
                } else if (key.isReadable()) {  
                        read(key);  
                }  
  
            }  
  
        }  
	}
	
	 public void read(SelectionKey key) throws IOException{
		   // 服务器可读取消息:得到事件发生的Socket通道  
		   SocketChannel channel = (SocketChannel) key.channel();
		   // 创建读取的缓冲区  
		   ByteBuffer byteBuffer = ByteBuffer.allocate(100);
		   channel.read(byteBuffer);
		   
		   byte[] data = byteBuffer.array();
		   
		   String msg = new String(data).trim();
		   
		   System.out.println("客户端接收到的消息:"+msg);
		   ByteBuffer msgBuffer = ByteBuffer.wrap(msg.getBytes());
		   
		   channel.write(msgBuffer);
		   
	   }
	
	public static void main(String[] args) throws IOException {
		 NIOClient client = new NIOClient();  
	        client.initClient("localhost",8000);  
	        client.listen();  

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值