Java Socket Programming Instance (v)-NIO UDP practice _java

Source: Internet
Author: User
Tags prepare socket static class

First, the return protocol interface and UDP 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.net.SocketAddress; 
Import java.nio.channels.*; 
Import Java.nio.ByteBuffer; 
 
Import java.io.IOException; public class Udpechoselectorprotocol implements <span style= "FONT-SIZE:1EM; line-height:1.5; " >echoprotocol </span><span style= "FONT-SIZE:1EM; line-height:1.5; " >{</span> private static final int echomax = 255;//Maximum size of Echo datagram static class Clientrec 
    Ord {public socketaddress clientaddress; 
  Public Bytebuffer buffer = bytebuffer.allocate (Echomax);  public void Handleaccept (Selectionkey key) throws IOException {} public void Handleread (Selectionkey 
    Key) throws IOException {Datagramchannel channel = (Datagramchannel) key.channel (); 
    Clientrecord Clntrec = (Clientrecord) key.attachment (); ClntRec.buffer.clear (); 
    Prepare buffer for receiving clntrec.clientaddress = channel.receive (Clntrec.buffer); if (clntrec.clientaddress!= null) {//Did we receive something? 
    Register write with the selector key.interestops (selectionkey.op_write); } public void Handlewrite (Selectionkey key) throws IOException {Datagramchannel channel = (datagramchannel 
    ) Key.channel (); 
    Clientrecord Clntrec = (Clientrecord) key.attachment (); ClntRec.buffer.flip (); 
    Prepare buffer for sending int bytessent = Channel.send (Clntrec.buffer, clntrec.clientaddress); 
      if (bytessent!= 0) {//Buffer completely written? 
    No longer interested in writes Key.interestops (Selectionkey.op_read);

 } 
  } 
 
}

two, NIO UDP clients:

Import java.net.InetSocketAddress; 
Import java.net.SocketException; 
Import Java.nio.ByteBuffer; 
 
Import Java.nio.channels.DatagramChannel; 
  public class Udpechoclientnonblocking {private static final int TIMEOUT = 3000;//Resend TIMEOUT (milliseconds) private static final int maxtries = 255; Maximum retransmissions public static void Main (String args[]) throws Exception {//Convert input String t 
 
    o bytes using the default charset byte[] bytestosend = "0123456789abcdefghijklmnopqrstuvwxyz". GetBytes (); 
    Create channel and set to nonblocking datagramchannel Datagramchannel = Datagramchannel.open (); 
    Datagramchannel.configureblocking (FALSE); 
     
    Datagramchannel.socket (). Setsotimeout (TIMEOUT); 
    Bytebuffer writebuf = Bytebuffer.wrap (bytestosend); 
     
    Bytebuffer readbuf = bytebuffer.allocate (maxtries); 
 
    Datagramchannel = Datagramchannel.connect (New inetsocketaddress ("127.0.0.1", 5500)); int TOTALBYTESRCVD = 0; //Total Bytes received so far int bytesrcvd;  
        Bytes received in last read while (Totalbytesrcvd < bytestosend.length) {if (writebuf.hasremaining ()) { 
      Datagramchannel.write (WRITEBUF); } if ((Bytesrcvd = Datagramchannel.read (readbuf)) = = 1) {throw new SocketException ("Connection closed PR 
      Ematurely "); 
      } TOTALBYTESRCVD + = BYTESRCVD; System.out.print ("."); 
    Do something Else} System.out.println ("Received:" + New String (Readbuf.array (), 0, TOTALBYTESRCVD)); 
  Datagramchannel.close ();

 } 
}

three, NIO UDP server side:

Import java.io.IOException; 
Import java.net.InetSocketAddress; 
Import java.nio.channels.*; 
 
Import Java.util.Iterator; public class Udpechoserverselector {private static final int TIMEOUT = 3000.//wait TIMEOUT (milliseconds) pub 
    Lic static void Main (string[] args) throws IOException {//Create a selector to multiplex client connections. 
 
    Selector Selector = Selector.open (); 
    Datagramchannel channel = Datagramchannel.open (); 
    Channel.configureblocking (FALSE); 
    Channel.socket (). bind (New Inetsocketaddress (5500)); 
 
    Channel.register (selector, selectionkey.op_read, New Udpechoselectorprotocol.clientrecord ()); 
    Udpechoselectorprotocol Echoselectorprotocol = new Udpechoselectorprotocol (); while (true) {//Run forever, receiving and echoing datagrams//wait for task or until timeout if (Selector.select (TIMEOUT) = = 0) 
        {System.out.print ("."); 
      Continue }//Get iterator on set of KeYs with I/O to process iterator<selectionkey> Keyiter = Selector.selectedkeys (). iterator (); while (Keyiter.hasnext ()) {Selectionkey key = Keyiter.next ();//The key is bit mask//Client socket CHA 
        Nnel has pending data? 
 
        if (key.isreadable ()) Echoselectorprotocol.handleread (key); 
        Client socket channel is available to writing and//key is valid (i.e., channel not closed). 
 
        if (Key.isvalid () && key.iswritable ()) Echoselectorprotocol.handlewrite (key); 
      Keyiter.remove ();

 } 
    } 
  } 
 
}

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.