package com.nio.t; 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. Use NIO to complete the three cores of network communication: * * 1. Channel: responsible for connection * * java.nio.channels.Channel interface: * |--SelectableChannel * |--SocketChannel * |--ServerSocketChannel //TCP * |--DatagramChannel //UDP * * |--Pipe.SinkChannel * |--Pipe.SourceChannel * * 2. Buffer: responsible for data access * * 3. Selector: It is a multiplexer of SelectableChannel. Used to monitor the IO status of SelectableChannel * */ public class TestBlockingNIO { // Client public void client() throws IOException{ // 1. Get channel SocketChannel sChannel = SocketChannel.open( new InetSocketAddress( " 127.0.0.1 " , 9898 )); // At this time, all files are in FileChannel FileChannel inChannel = FileChannel.open(Paths.get ( " D :\\1.txt " ), StandardOpenOption.READ); // 2. Allocate a buffer of the specified size ByteBuffer buf = ByteBuffer.allocate( 1024 ); // 3. Read the local file and send it to the server while (inChannel.read(buf) != - 1 ){ // The file in FileChannel is read into the buffer buf.flip(); sChannel.write(buf); // Write the data in the buffer to the SocketChannel buf.clear(); // Empty the buffer } // After the loop, all files are sent to the SocketChannel // 4. Close channel inChannel.close(); sChannel.close(); } // Server public void server() throws IOException{ // 1. Get the channel, indicating that a ServerSocketChannel channel is opened on the machine ServerSocketChannel ssChannel = ServerSocketChannel.open(); // Indicates that an empty file is created locally, waiting for data to be written FileChannel outChannel = FileChannel.open(Paths.get ( " D :\\2.txt " ), StandardOpenOption.WRITE, StandardOpenOption.CREATE); // 2. Bind the port ssChannel.bind( new InetSocketAddress( 9898 )); // 3. Get the channel connected by the client, when the connection is established with the client, SocketChannel sChannel = ssChannel.accept(); // 4. Allocate a buffer of the specified size ByteBuffer buf = ByteBuffer.allocate( 5 ); // 5. Receive the client's data and save it to the local while (sChannel.read(buf) != - 1 ){ try { Thread.sleep(5000); }catch (Exception e){ } buf.flip(); outChannel.write(buf); // Write the data in the buffer to the file buf.clear(); } // 6. Close the channel sChannel.close(); outChannel.close(); ssChannel.close(); } public static void main(String[] args) { new Thread(()->{ try { new TestBlockingNIO().client(); System.out.println("client end...."); }catch (Exception e){ } }).start(); new Thread(()->{ try { new TestBlockingNIO().server(); System.out.println("server end ....."); }catch (Exception e){ } }).start(); } }