JAVA-7NIO之Socket/ServerSocket Channel,niosocketchannel

來源:互聯網
上載者:User

JAVA-7NIO之Socket/ServerSocket Channel,niosocketchannel
一、ServerSocketChannel

Java NIO中的 ServerSocketChannel 是一個可以監聽新進來的TCP串連的通道, 就像標準IO中的ServerSocket一樣。ServerSocketChannel類在 java.nio.channels包中。

開啟 ServerSocketChannel

通過調用 ServerSocketChannel.open() 方法來開啟ServerSocketChannel.

關閉 ServerSocketChannel

通過調用ServerSocketChannel.close() 方法來關閉ServerSocketChannel. 

監聽新進來的串連

通過 ServerSocketChannel.accept() 方法監聽新進來的串連。當 accept()方法返回的時候,它返回一個包含新進來的串連的 SocketChannel。因此, accept()方法會一直阻塞到有新串連到達。

通常不會僅僅只監聽一個串連,在while迴圈中調用 accept()方法. 

當然,也可以在while迴圈中使用除了true以外的其它退出準則。

非阻塞模式

ServerSocketChannel可以設定成非阻塞模式。在非阻塞模式下,accept() 方法會立刻返回,如果還沒有新進來的串連,返回的將是null。 因此,需要檢查返回的SocketChannel是否是null.如:

    /**     * socket server channel     */    @Test    public void text2() throws IOException {        ServerSocketChannel channel = ServerSocketChannel.open();    //建立channel        channel.socket().bind(new InetSocketAddress(9999));     //監聽連接埠        channel.configureBlocking(true);                             //設定阻塞        while (true) {            SocketChannel accept = channel.accept();                    //設定為阻塞,則此方法阻塞,直到有串連            //如果設定為非阻塞,需要在這裡判斷 accept == null?            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);            accept.read(byteBuffer);            byteBuffer.flip();                                    //反轉            while (byteBuffer.hasRemaining()) {                   //判斷                System.err.println((char)byteBuffer.get());       //輸出            }        }    }

 

二、SocketChannel

Java NIO中的SocketChannel是一個串連到TCP網路通訊端的通道。可以通過以下2種方式建立SocketChannel:

開啟 SocketChannel

下面是SocketChannel的開啟檔案:

關閉 SocketChannel

當用完SocketChannel之後調用SocketChannel.close()關閉SocketChannel:

從 SocketChannel 讀取資料

要從SocketChannel中讀取資料,調用一個read()的方法之一。

首先,分配一個Buffer。從SocketChannel讀取到的資料將會放到這個Buffer中。

然後,調用SocketChannel.read()。該方法將資料從SocketChannel 讀到Buffer中。read()方法返回的int值表示讀了多少位元組進Buffer裡。如果返回的是-1,表示已經讀到了流的末尾(串連關閉了)。

寫入 SocketChannel

寫資料到SocketChannel用的是SocketChannel.write()方法,該方法以一個Buffer作為參數。

注意SocketChannel.write()方法的調用是在一個while迴圈中的。Write()方法無法保證能寫多少位元組到SocketChannel。所以,我們重複調用write()直到Buffer沒有要寫的位元組為止。

非阻塞模式

可以設定 SocketChannel 為非阻塞模式(non-blocking mode).設定之後,就可以在非同步模式下調用connect(), read() 和write()了。

connect()

如果SocketChannel在非阻塞模式下,此時調用connect(),該方法可能在串連建立之前就返回了。為了確定串連是否建立,可以調用finishConnect()的方法。

 write()

非阻塞模式下,write()方法在尚未寫出任何內容時可能就返回了。所以需要在迴圈中調用write()。前面已經有例子了,這裡就不贅述了。

read()

非阻塞模式下,read()方法在尚未讀取到任何資料時可能就返回了。所以需要關注它的int傳回值,它會告訴你讀取了多少位元組。

非阻塞模式與選取器

非阻塞模式與選取器搭配會工作的更好,通過將一或多個SocketChannel註冊到Selector,可以詢問選取器哪個通道已經準備好了讀取,寫入等。Selector與SocketChannel的搭配使用會在後面詳講。

/**     * socket channel     */    @Test    public void test3() throws IOException {        SocketChannel channel = SocketChannel.open();                               //建立服務端        channel.connect(new InetSocketAddress("127.0.0.1",9999));   //串連服務端地址        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);  //緩衝區        byteBuffer.put("123".getBytes());        byteBuffer.flip();                                  //反轉        while (byteBuffer.hasRemaining()) {                 //判斷            channel.write(byteBuffer);        }    }

 

聯繫我們

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