Socket Demo__java Base for Aio--java asynchronous IO

Source: Internet
Author: User
Tags throwable

http://blog.csdn.net/xxb2008

Package com.vdebug.aio.socket;
Import java.io.IOException;
Import java.net.InetSocketAddress;
Import java.net.StandardSocketOptions;
Import Java.nio.ByteBuffer;
Import Java.nio.CharBuffer;
Import Java.nio.channels.AsynchronousServerSocketChannel;
Import Java.nio.channels.AsynchronousSocketChannel;
Import Java.nio.channels.CompletionHandler;
Import Java.nio.charset.Charset;

Import Java.nio.charset.CharsetDecoder;
 /** * Created by PC on 2015/1/5.
    */public class Server {static int PORT = 8080;
    static int buffer_size = 1024; static String CHARSET = "Utf-8"; The default encoding static Charsetdecoder decoder = Charset.forname (Charset). Newdecoder ();
    decode int port;
    Bytebuffer buffer;

    Asynchronousserversocketchannel Serverchannel;
        public Server (int port) throws IOException {this.port = port;
        This.buffer = Bytebuffer.allocate (buffer_size);
    This.decoder = Charset.forname (Charset). Newdecoder (); private void Listen () throws Exception {//Open a service channel//BIND service Port This.serverchannel = Asynchronousserversocketchannel.open (). bind (New Inet
        SocketAddress (port), 100);

        This.serverChannel.accept (This, new Accepthandler ()); Thread t = new Thread (new Runnable () {@Override public void run () {while (true)
                    {System.out.println ("running ...");
                    try {thread.sleep (2000);
                    catch (Interruptedexception e) {e.printstacktrace ();
        }
                }
            }
        });

    T.start (); /** * Accept callback to a request * * Private class Accepthandler implements COMPLETIONHANDLER<ASYNCHRONOUSSOC Ketchannel, server> {@Override public void completed (final Asynchronoussocketchannel client, Server at Tachment) {try {System.out.println ("Remote address:" + client.getremoteaddress ());
                TCP parameters Client.setoption (Standardsocketoptions.tcp_nodelay, true);
                Client.setoption (STANDARDSOCKETOPTIONS.SO_SNDBUF, 1024);

                Client.setoption (STANDARDSOCKETOPTIONS.SO_RCVBUF, 1024);
                    if (Client.isopen ()) {System.out.println ("Client.isopen:" + client.getremoteaddress ());
                    Final Bytebuffer buffer = bytebuffer.allocate (buffer_size);
                    Buffer.clear ();
                Client.read (buffer, client, new Readhandler (buffer));
            } catch (Exception e) {e.printstacktrace ();
            Finally {attachment.serverChannel.accept (attachment, this);//Listen for new requests, recursive calls.
                @Override public void failed (Throwable exc, Server attachment) {try {
            Exc.printstacktrace (); finally {attachment.serverChannel.accept (attAchment, this);//Listen for new requests, recursive calls. }}/** * read to request data callback * * Private class Readhandler implements Completionhandler<integ

        Er, asynchronoussocketchannel> {private Bytebuffer buffer;
        Public Readhandler (Bytebuffer buffer) {this.buffer = buffer;  @Override public void completed (Integer result, asynchronoussocketchannel attachment) {try
                {if (Result < 0) {//client closes the connection server.close (attachment);
                    else if (result = = 0) {System.out.println ("null data");//processing NULL data} else {
                    Read the request, processing the data sent by the client Buffer.flip ();
                    Charbuffer Charbuffer = Server.decoder.decode (buffer); System.out.println (Charbuffer.tostring ());
                    Receive request//response action, server response result Buffer.clear (); String res = "http/1.1 OK "+" \r\n\r\n "+" Hellworld ";
                    Buffer = Bytebuffer.wrap (Res.getbytes ());
                Attachment.write (buffer, attachment, new Writehandler (buffer);//response: Response.
            } catch (Exception e) {e.printstacktrace ();
            @Override public void failed (Throwable exc, asynchronoussocketchannel attachment) {
            Exc.printstacktrace ();
        Server.close (attachment); }/** * Write a callback that responds to the request/private class Writehandler implements Completionhandler<integer, Asyn

        chronoussocketchannel> {private Bytebuffer buffer;
        Public Writehandler (Bytebuffer buffer) {this.buffer = buffer; @Override public void completed (Integer result, asynchronoussocketchannel attachment) {BUF
            Fer.clear ();
        Server.close (attachment); } @Override public void failEd (throwable exc, asynchronoussocketchannel attachment) {exc.printstacktrace ();
        Server.close (attachment);
            } public static void Main (string[] args) {try {System.out.println ("Starting service ...");
            Server server = new server (PORT);
        Server.listen ();
        catch (Exception e) {e.printstacktrace ();
        } private static void Close (Asynchronoussocketchannel client) {try {client.close ();
        catch (Exception e) {e.printstacktrace ();
 }
    }
}



I understand synchronous \ Asynchronous Operations | Blocking io\ non-blocking IO

Sync blocking

Sync non-blocking

http://blog.csdn.net/xxb2008 Asynchronous non-blocking

http://blog.csdn.net/xxb2008

Related Article

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.