Java Socket Programming Instance (d)-NIO TCP Practice _java

Source: Internet
Author: User

First, the Return protocol interface and TCP mode implementation:

1. Interface:

Import Java.nio.channels.SelectionKey; 
Import java.io.IOException; 
 
Public interface Echoprotocol { 
 void handleaccept (Selectionkey key) throws IOException; 
 void Handleread (Selectionkey key) throws IOException; 
 void Handlewrite (Selectionkey key) throws IOException; 

2. Implementation:

Import java.nio.channels.*; 
Import Java.nio.ByteBuffer; 
 
Import java.io.IOException; public class Tcpechoselectorprotocol implements echoprotocol{private int bufsize;//Size of I/O buffer public Ec 
  Hoselectorprotocol (int bufsize) {this.bufsize = bufsize; The public void handleaccept (Selectionkey key) throws IOException {Socketchannel = (Clntchan 
    ) Key.channel ()). Accept (); Clntchan.configureblocking (FALSE); Must be nonblocking to register//register the selector with new channel for read and attach byte buffer cln 
     
  Tchan.register (Key.selector (), Selectionkey.op_read, Bytebuffer.allocate (bufsize)); public void Handleread (Selectionkey key) throws IOException {//Client socket channel has pending data S 
    Ocketchannel Clntchan = (socketchannel) key.channel (); 
    Bytebuffer buf = (bytebuffer) key.attachment (); 
    Long bytesread = Clntchan.read (BUF); if (bytesread = = 1) {//Did the other End close? 
    Clntchan.close (); 
      else if (Bytesread > 0) {//indicate via key that reading/writing are both of interest now. Key.interestops (Selectionkey.op_read | 
    Selectionkey.op_write); } public void Handlewrite (Selectionkey key) throws IOException {/* * Channel is available for writin 
     g, and key is valid (i.e., client Channel * not closed). 
    *///Retrieve data read earlier Bytebuffer BUF = (bytebuffer) key.attachment (); Buf.flip (); 
    Prepare buffer for writing Socketchannel Clntchan = (socketchannel) key.channel (); 
    Clntchan.write (BUF);  
      if (!buf.hasremaining ()) {//Buffer completely written? 
    Nothing left, so no longer interested in writes Key.interestops (Selectionkey.op_read); } buf.compact ();  Make room for more data to is read in}}

Two, NIO TCP clients:

Import java.net.InetSocketAddress; 
Import java.net.SocketException; 
Import Java.nio.ByteBuffer; 
 
Import Java.nio.channels.SocketChannel; public class Tcpechoclientnonblocking {public static void main (String args[]) throws Exception {string server = "127.0.0.1"; Server name or IP address//Convert input String to bytes using the default charset byte[] argument = "01234 
 
    56789abcdefghijklmnopqrstuvwxyz ". GetBytes (); 
 
    int servport = 5500; 
    Create channel and set to nonblocking socketchannel Clntchan = Socketchannel.open (); 
 
    Clntchan.configureblocking (FALSE); Initiate connection to server and repeatedly poll until complete if (!clntchan.connect (new inetsocketaddress 
    R, Servport)) {while (!clntchan.finishconnect ()) {System.out.print (".");//do something else} 
    } Bytebuffer writebuf = bytebuffer.wrap (argument); 
    Bytebuffer readbuf = bytebuffer.allocate (argument.length); IntTOTALBYTESRCVD = 0; Total Bytes received so far int bytesrcvd; 
        Bytes received in last read while (Totalbytesrcvd < argument.length) {if (writebuf.hasremaining ()) { 
      Clntchan.write (WRITEBUF); } if ((Bytesrcvd = Clntchan.read (readbuf)) = = 1) {throw new SocketException ("Connection closed premature 
      Ly "); 
      } TOTALBYTESRCVD + = BYTESRCVD; System.out.print (".");  Do something Else} System.out.println ("Received:" +//Convert to String per default charset new 
    String (Readbuf.array (), 0, TOTALBYTESRCVD). Length ()); 
  Clntchan.close (); 

 } 
}

Tri, NIO TCP server side:

Import java.io.IOException; 
Import java.net.InetSocketAddress; 
Import java.nio.channels.*; 
 
Import Java.util.Iterator;  public class Tcpserverselector {private static final int bufsize = 256;//Buffer size (bytes) private static final int TIMEOUT = 3000; Wait timeout (milliseconds) public static void main (string[] args) throws IOException {int[] ports = {5500 
    }; 
 
    Create a selector to multiplex listening sockets and connections selector = selector (); Create listening socket channel for each port and register selector for (int port:ports) {Serversocketch 
      Annel Listnchannel = Serversocketchannel.open (); 
      Listnchannel.socket (). bind (New Inetsocketaddress (port)); Listnchannel.configureblocking (FALSE); Must is nonblocking to register//register selector with channel. 
    The returned key is ignored Listnchannel.register (selector, selectionkey.op_accept); //Create a handler THat would implement the protocol Tcpprotocol protocol = new Tcpechoselectorprotocol (bufsize); while (true) {//Run forever, processing available I/O operations//wait for some channel to be ready (or timeout 
        ) if (Selector.select (TIMEOUT) = = 0) {//returns # of Ready Chans System.out.print ("."); 
      Continue }//Get iterator on the set of keys with I/O to process iterator<selectionkey> Keyiter = Selector.selec 
      Tedkeys (). iterator (); while (Keyiter.hasnext ()) {Selectionkey key = Keyiter.next ();//key is bit mask//Server socket Chann 
        El has pending connection requests? 
          if (key.isacceptable ()) {System.out.println ("----accept-----"); 
        Protocol.handleaccept (key); 
        }//Client socket channel has pending data? 
          if (key.isreadable ()) {System.out.println ("----Read-----"); 
        Protocol.handleread (key); }//ClieNT Socket channel is available to writing and//key is valid (i.e., channel not closed)? 
          if (Key.isvalid () && key.iswritable ()) {System.out.println ("----Write-----"); 
        Protocol.handlewrite (key); } keyiter.remove (); 

 Remove from set of selected Keys}}}

The above is the entire contents of this article, see more Java syntax, you can pay attention to: "Thinking in the Java Chinese manual", "JDK 1.7 reference manual in English," "JDK 1.6 API Java Chinese Reference manual", "JDK 1.5 API Java Chinese reference manual, but also hope that we support the cloud-dwelling community.

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.