怎么理解Netty中的NIO阻塞通信

本篇内容主要讲解“怎么理解Netty中的NIO阻塞通信”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么理解Netty中的NIO阻塞通信”吧!

NIO 完成网络通信的三个核心:Channel、Buffer、Selector

1、通道(Channel):负责连接

SocketChannel、ServerSocketChannel、DatagramChannel、Pipe.SinkChannel、Pipe.SourceChannel

2、缓冲区(Buffer):负责数据的存取

3、 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况
1、阻塞网络通信copy数据
//客户端
@Test
public void client() throws IOException{
   //1. 获取通道
   SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8085));
   
   FileChannel inChannel = FileChannel.open(Paths.get("/Users/tentsuuhou/Desktop/777.txt"), StandardOpenOption.READ);
   
   //2. 分配指定大小的缓冲区
   ByteBuffer buf = ByteBuffer.allocate(1024);
   
   //3. 读取本地文件,并发送到服务端
   while(inChannel.read(buf) != -1){
      buf.flip();
      sChannel.write(buf);
      buf.clear();
   }
   
   //4. 关闭通道
   inChannel.close();
   sChannel.close();
}

//服务端
@Test
public void server() throws IOException{
   //1. 获取通道
   ServerSocketChannel ssChannel = ServerSocketChannel.open();
   
   FileChannel outChannel = FileChannel.open(Paths.get("/Users/tentsuuhou/Desktop/666.txt"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
   
   //2. 绑定连接
   ssChannel.bind(new InetSocketAddress(8085));
   
   //3. 获取客户端连接的通道
   SocketChannel sChannel = ssChannel.accept();
   
   //4. 分配指定大小的缓冲区
   ByteBuffer buf = ByteBuffer.allocate(1024);
   
   //5. 接收客户端的数据,并保存到本地
   while(sChannel.read(buf) != -1){
      buf.flip();
      outChannel.write(buf);
      buf.clear();
   }
   
   //6. 关闭通道
   sChannel.close();
   outChannel.close();
   ssChannel.close();
}

先开启server端,在开启client端,这样就ok了

2、阻塞简单版client发送server数据
//客户端
@Test
public void client() throws IOException{
   SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

   ByteBuffer buf = ByteBuffer.allocate(1024);

   sChannel.shutdownOutput();
   
   //接收服务端的反馈
   int len = 0;
   while((len = sChannel.read(buf)) != -1){
      buf.flip();
      System.out.println(new String(buf.array(), 0, len));
      buf.clear();
   }
   
   sChannel.close();
}

//服务端
@Test
public void server() throws IOException{
   ServerSocketChannel ssChannel = ServerSocketChannel.open();

   ssChannel.bind(new InetSocketAddress(8080));
   
   SocketChannel sChannel = ssChannel.accept();
   
   ByteBuffer buf = ByteBuffer.allocate(1024);

   
   //发送反馈给客户端
   buf.put("服务端接收数据成功".getBytes());
   buf.flip();
   sChannel.write(buf);
   
   sChannel.close();
   ssChannel.close();
}

client中,sChannel.shutdownOutput(); 如果没有这个,处于阻塞状态,server不知道,只有shutdownOutput()才能提醒server端,这样就能把client的数据传到server中。

怎么理解Netty中的NIO阻塞通信

到此,相信大家对“怎么理解Netty中的NIO阻塞通信”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!