NIO 完成網絡通訊的三個核心:Channel、Buffer、Selector網絡
負責鏈接併發
SocketChannel、ServerSocketChannel、DatagramChannel、Pipe.SinkChannel、Pipe.SourceChannelspa
負責數據的存取server
是 SelectableChannel 的多路複用器。用於監控 SelectableChannel 的 IO 情況blog
//客戶端 @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了ip
五、阻塞簡單版client發送server數據get
//客戶端 @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中。it