JAVA高階基礎(51)---有反饋的阻塞式的IO網路通訊
阿新 • • 發佈:2018-12-15
package org.lanqiao.blocking2.demo; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /* * 1. 獲取通道 2. 分配指定大小的緩衝區 3. 讀取本地檔案,併發送到服務端 4. 關閉通道 */ public class Client { public static void main(String[] args) throws IOException { System.out.println("客戶端啟動...."); //1 獲取通道 SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898)); //2 分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //3 讀取本地檔案,併發送到服務端 FileChannel fChannel = FileChannel.open(Paths.get("aa.jpg"), StandardOpenOption.READ); while((fChannel.read(buf)) != -1) { buf.flip(); sChannel.write(buf); buf.clear(); } //告知服務端傳送資料完畢 sChannel.shutdownOutput(); //3.1 接收服務端的反饋內容 while(sChannel.read(buf) != -1) { buf.flip(); byte[] b = buf.array(); System.out.println(new String(b,0,buf.limit())); } //4 關閉通道 fChannel.close(); sChannel.close(); } }
package org.lanqiao.blocking2.demo; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /**服務端: 1. 獲取通道 2. 繫結連線 3. 獲取客戶端連線的通道 4. 分配指定大小的緩衝區 5. 接收客戶端的資料,並儲存到本地 6. 關閉通道 */ public class Server { public static void main(String[] args) throws IOException { System.out.println("服務端啟動..."); //1 獲取通道 ServerSocketChannel ssChannel = ServerSocketChannel.open(); //2 繫結連結 ssChannel.bind(new InetSocketAddress( 9898)); // 3 獲取客戶端的通道 SocketChannel sChannel = ssChannel.accept(); //4分配指定大小的緩衝區 ByteBuffer buf = ByteBuffer.allocate(1024); //5 接收客戶端的資料, 並儲存到本地 FileChannel fChannel = FileChannel.open(Paths.get("aaCopy.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE); while((sChannel.read(buf)) != -1) { buf.flip(); fChannel.write(buf); buf.clear(); } //5.1 向客戶端傳送反饋內容 buf.put("接收成功".getBytes()); buf.flip(); sChannel.write(buf); //6 關閉通道 ssChannel.close(); fChannel.close(); sChannel.close(); } }