NIO 基礎

Java NIO 由以下幾個核心部分組成:
Channels
Buffers
Selectors
此系列的文章參考并發變成網的內容 http://ifeve.com/overview/
還有我同事寫的幾篇文章 http://www.lxweimin.com/p/12c81abb5387

下面是socket通信的例子

public static class ClientSocket implements Runnable {
        public void run() {
            try {
               //SocketChannel的打開方式
                SocketChannel socketChannel = SocketChannel.open();
                socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
                String newData = "New String to write to file..." + System.currentTimeMillis();
                ByteBuffer buf = ByteBuffer.allocate(48);//分配48字節capacity的ByteBuffer
                buf.clear();//情況buffer,進行寫入
                buf.put(newData.getBytes());//buffer添加內容
                buf.flip();//執行此方法,使buffer進入讀狀態
                while (buf.hasRemaining()) {//判斷buffer是不是讀取完
                    socketChannel.write(buf);//將buffer內容讀取到channel中
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static class ServerSocket implements Runnable {
        public void run() {
            ServerSocketChannel serverSocketChannel;
            try {
                serverSocketChannel = ServerSocketChannel.open();//打開socket服務端
                serverSocketChannel.socket().bind(new InetSocketAddress(9999));
                //ServerSocketChannel可以設置成非阻塞模式。在非阻塞模式下,accept() 方法會立刻返回,如果還沒有新進來的連接,返回的將是null
                //serverSocketChannel.configureBlocking(false);
                while (true) {
                     //監聽新進來的連接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    ByteBuffer buf = ByteBuffer.allocate(48);
                    int bytesRead = socketChannel.read(buf);將通道信息寫入buffer
                    while (bytesRead != -1) {//讀取buffer
                        System.out.println("Read " + bytesRead);
                        buf.flip();
                        while (buf.hasRemaining()) {
                            System.out.print((char) buf.get());
                        }
                        buf.clear();
                        bytesRead = socketChannel.read(buf);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。