【Java nio】 Blocking nio

admin2024-10-07  25

 1 package com.slp.nio;
 2 
 3 
 4 import org.junit.Test;
 5 
 6 import java.io.File;
 7 import java.io.IOException;
 8 import java.net.InetSocketAddress;
 9 import java.nio.ByteBuffer;
10 import java.nio.channels.FileChannel;
11 import java.nio.channels.ServerSocketChannel;
12 import java.nio.channels.SocketChannel;
13 import java.nio.file.Paths;
14 import java.nio.file.StandardOpenOption;
15 
16 /**
17  * Created by sanglp on 2017/3/1.
18  * 一、使用NIO完成网络通信的三个核心
19  * 1、通道:负责连接
20  *     |--java.nio.channels.channel接口
21  *        |--SelectableChannel
22  *           |--SocketChannel
23  *           |--ServerSocketChannel
24  *           |--DatagramChannel
25  *
26  *           |--Pipe.SinkChannel
27  *           |--Pipe.SourceChannel
28  * 2、缓冲区:负责数据的存取
29  * 3、选择器:是SelectableChannel的多路复用器,用于监控SelectableChannel的IO状况
30  *
31  */
32 public class TestBlockingNIO {
33     //客户端
34     @org.junit.Test
35     public void client() throws IOException {
36       // 1、获取通道
37        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
38         FileChannel inChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);
39         //2、分配指定大小的缓冲区
40         ByteBuffer buffer =ByteBuffer.allocate(1024);
41         //3、读取本地文件 并发送到服务端
42         while (inChannel.read(buffer)!=-1){
43             buffer.flip();
44             socketChannel.write(buffer);
45             buffer.clear();
46         }
47         //4、关闭通道
48         socketChannel.close();
49         inChannel.close();
50     }
51     //服务端
52     @Test
53     public void server() throws IOException {
54         //1、获取通道
55         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
56         FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
57         //2、绑定连接
58         serverSocketChannel.bind(new InetSocketAddress(9898));
59         //3、获取客户端连接
60         SocketChannel socketChannel = serverSocketChannel.accept();
61         //4、分配指定大小的缓冲区
62         ByteBuffer buffer = ByteBuffer.allocate(1024);
63 
64         //5、接收客户端的数据,并保存到本地
65 
66         while (socketChannel.read(buffer)!=-1){
67             buffer.flip();
68             outChannel.write(buffer);
69             buffer.clear();
70         }
71         //关闭通道
72         socketChannel.close();
73         serverSocketChannel.close();
74 
75     }
76 }

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!