Javanio Blocking IO Add server feedback

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.