Java-NIO-网络通信-阻塞

来源:互联网 发布:淘宝金冠店多少 编辑:程序博客网 时间:2024/06/05 19:28
使用NIO完成网络通信的三个核心
 * 1. 通道(Channel):负责连接
 *        java.nio.channels.Channel 接口:
 *             |--SelectableChannel
 *                 |--SocketChannel
 *                 |--ServerSocketChannel
 *                 |--DatagramChannel
 *
 *                 |--Pipe.SinkChannel
 *                 |--Pipe.SourceChannel
 *
 * 2. 缓冲区(Buffer):负责数据的存取

 * 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况

@Test public void client() throws IOException{ //1.获取通道 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));  FileChannel channel = FileChannel.open(Paths.get("Java.pdf"),StandardOpenOption.READ);  //2.分配指定大小的缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024);  //3.读取本地文件并发送到客户端 while((channel.read(buf))!=-1){ buf.flip(); socketChannel.write(buf); buf.clear(); }  //4.接收服务端的反馈 socketChannel.shutdownOutput();  int len = 0; while((len = socketChannel.read(buf))!=-1){ buf.flip(); System.out.println(new String(buf.array(),0,len)); buf.clear(); }  //5.关闭通道 channel.close(); socketChannel.close(); }  @Test public void server() throws IOException{  //1.获取通道 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  FileChannel fileChannel = FileChannel.open(Paths.get("JavaCopy.pdf"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);  //2.绑定连接 serverSocketChannel.bind(new InetSocketAddress(9898));  //3.获取客户端连接通道 SocketChannel scChannel = serverSocketChannel.accept();  //4.分配缓冲区 ByteBuffer buf = ByteBuffer.allocate(1024);  //5.接收并保存到本地 while (scChannel.read(buf)!=-1) { buf.flip(); fileChannel.write(buf); buf.clear(); }  //6.发送反馈给客户端 buf.put("服务端接收数据成功...".getBytes()); buf.flip(); scChannel.write(buf);  //7.关闭通道 scChannel.close(); fileChannel.close(); serverSocketChannel.close(); }




阅读全文
0 0