Package Com.java.nio;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;import Org.junit.test;public class Testblockingnio {@Test//clients public void Client () throws IOEXCEPTION{//1. Get channel Socketchannel SChannel = Socketchannel.open (New inetsocketaddress ("127.0.0.1", 1008)); FileChannel Inchannel = Filechannel.open (Paths.get ("1.jpg"), Standardopenoption.read),//2. Allocates a buffer of the specified size Bytebuffer buf = Bytebuffer.allocate (1024);//3. Reads the local file and sends it to the server while (Inchannel.read (BUF)!=-1) {buf.flip (); Schannel.write (BUF); Buf.clear ();} Open non-blocking mode schannel.shutdownoutput ();//Receive server feedback int len = 0; while (len = Schannel.read (buf))!=-1) {buf.flip (); System.out.println (New String (Buf.array (), 0,len)); Buf.clear ();} 4. Close the channel inchannel.close (); Schannel.close ();} @Test//server public void Server () throws IOEXCEPTION{//1. GetChannel Serversocketchannel Sschannel = Serversocketchannel.open (); FileChannel Outchannel = Filechannel.open (Paths.get ("2.jpg"), Standardopenoption.write,standardopenoption.create) ;//2. Bind Link Sschannel.bind (new inetsocketaddress (1008));//3. Gets the client connection channel Socketchannel SChannel = Sschannel.accept ();//4. Allocates a buffer of the specified size Bytebuffer buf =bytebuffer.allocate (1024);//5. Receive customer data and save to local while (Schannel.read (BUF)!=-1) {buf.flip (); O Utchannel.write (BUF); Buf.clear ();} Send feedback to client buf.put ("Server received data successfully". GetBytes ()); Buf.flip (); Schannel.write (BUF);//6. Close channel Schannel.close (); O Utchannel.close (); Sschannel.close ();}}
Javanio Blocking IO Add server feedback