java NIO入門【原】

來源:互聯網
上載者:User

標籤:關閉   har   net   config   localhost   服務端   package   通道   log   

server
package com.server;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;public class Server {        public static void main(String[] args) throws Exception {        //建立TCP服務端        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();        //綁定TCP連接埠        serverSocketChannel.socket().bind(new InetSocketAddress(9999));        //配置成"非阻塞"        serverSocketChannel.configureBlocking(false);        while (true) {            //允許接收TCP連結            SocketChannel socketChannel = serverSocketChannel.accept();            //當有TCP串連上來時,擷取到的就不為空白            if (socketChannel != null) {                //寫英文資料"生命不步,戰鬥不息"                String newData = System.currentTimeMillis() + ": Cease to struggle and you cease to live .";                //開闢緩衝                ByteBuffer buf = ByteBuffer.allocate(1024);                //重設,準備寫入資料到緩衝                buf.clear();                //真正寫入資料到緩衝                buf.put(newData.getBytes());                //準備從緩衝讀取資料                buf.flip();                //如果讀到資料有剩餘                while (buf.hasRemaining()) {                    //真正從緩衝讀取資料,並寫入到通道中                    socketChannel.write(buf);                }            }        }    }}

 

 

client
package com.client;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;public class client {    public static void main(String[] args) throws Exception {        //建立TCP服務端        SocketChannel socketChannel = SocketChannel.open();        //連結到本地的8888連接埠        socketChannel.connect(new InetSocketAddress("localhost", 8888));        //開闢緩衝        ByteBuffer buf = ByteBuffer.allocate(1024);        //重設,準備寫入資料到緩衝        buf.clear();        //真正從通道讀取資料到緩衝        int bytesRead = socketChannel.read(buf);        //準備從緩衝讀取資料        buf.flip();        //如果讀到資料有剩餘        while (buf.hasRemaining()) {            //取一個位元組            byte b = (byte) (buf.get());            //轉成一個字元            System.out.print((char) b);        }        //關閉通道        socketChannel.close();    }}

 

java NIO入門【原】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.