Aio--Java非同步IO的 Socket Demo__Java基礎

來源:互聯網
上載者:User

 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"; //預設編碼    static CharsetDecoder decoder = Charset.forName(CHARSET).newDecoder(); //解碼    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 {        //開啟一個服務通道        //綁定服務連接埠        this.serverChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port), 100);        this.serverChannel.accept(this, new AcceptHandler());        Thread t = new Thread(new Runnable() {            @Override            public void run() {                while (true) {                    System.out.println("運行中...");                    try {                        Thread.sleep(2000);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        });        t.start();    }    /**     * accept到一個請求時的回調     */    private class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {        @Override        public void completed(final AsynchronousSocketChannel client, Server attachment) {            try {                System.out.println("遠程地址:" + client.getRemoteAddress());                //tcp各項參數                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);// 監聽新的請求,遞迴調用。            }        }        @Override        public void failed(Throwable exc, Server attachment) {            try {                exc.printStackTrace();            } finally {                attachment.serverChannel.accept(attachment, this);// 監聽新的請求,遞迴調用。            }        }    }    /**     * Read到請求資料的回調     */    private class ReadHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {        private ByteBuffer buffer;        public ReadHandler(ByteBuffer buffer) {            this.buffer = buffer;        }        @Override        public void completed(Integer result, AsynchronousSocketChannel attachment) {            try {                if (result < 0) {// 用戶端關閉了串連                    Server.close(attachment);                } else if (result == 0) {                    System.out.println("空資料"); // 處理空資料                } else {                    // 讀取請求,處理用戶端發送的資料                    buffer.flip();                    CharBuffer charBuffer = Server.decoder.decode(buffer);                    System.out.println(charBuffer.toString()); //接收請求                    //響應操作,伺服器響應結果                    buffer.clear();                    String res = "HTTP/1.1 200 OK" + "\r\n\r\n" + "hellworld";                    buffer = ByteBuffer.wrap(res.getBytes());                    attachment.write(buffer, attachment, new WriteHandler(buffer));//Response:響應。                }            } catch (Exception e) {                e.printStackTrace();            }        }        @Override        public void failed(Throwable exc, AsynchronousSocketChannel attachment) {            exc.printStackTrace();            Server.close(attachment);        }    }    /**     * Write響應完請求的回調     */    private class WriteHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {        private ByteBuffer buffer;        public WriteHandler(ByteBuffer buffer) {            this.buffer = buffer;        }        @Override        public void completed(Integer result, AsynchronousSocketChannel attachment) {            buffer.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("正在啟動服務...");            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();        }    }}


 

 


 

 

 

 

 

我理解的 同步\非同步作業 |  阻塞IO\非阻塞IO

  同步阻塞

 

同步非阻塞

 

 http://blog.csdn.net/xxb2008 非同步非阻塞

 

 

 

 http://blog.csdn.net/xxb2008

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.