Java NIO (9) ServerSocketChannel

來源:互聯網
上載者:User

標籤:tcp   log   com   ons   pac   package   stop   ica   open   

Java NIO ServerSocketChannel

A Java NIO ServerSocketChannel is a channel that can listen for incoming TCP connections, just like a ServerSocket in standard Java Networking. The ServerSocketChannel class is located in the java.nio.channelspackage.

Here is an example:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(9999));while(true){    SocketChannel socketChannel =            serverSocketChannel.accept();    //do something with socketChannel...}
Opening a ServerSocketChannel

You open a ServerSocketChannel by calling the ServerSocketChannel.open() method. Here is how that looks:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
Closing a ServerSocketChannel

Closing a ServerSocketChannel is done by calling the ServerSocketChannel.close() method. Here is how that looks:

serverSocketChannel.close();
Listening for Incoming Connections

Listening for incoming connections is done by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.

Since you are typically not interested in listening just for a single connection, you call the accept() inside a while-loop. Here is how that looks:

while(true){    SocketChannel socketChannel =            serverSocketChannel.accept();    //do something with socketChannel...}

Of course you would use some other stop-criteria than true inside the while-loop.

Non-blocking Mode

A ServerSocketChannel can be set into non-blocking mode. In non-blocking mode the accept() method returns immediately, and may thus return null, if no incoming connection had arrived. Therefore you will have to check if the returned SocketChannel is null. Here is an example:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();serverSocketChannel.socket().bind(new InetSocketAddress(9999));serverSocketChannel.configureBlocking(false);while(true){    SocketChannel socketChannel =            serverSocketChannel.accept();    if(socketChannel != null){        //do something with socketChannel...        }}

 

Java NIO (9) ServerSocketChannel

聯繫我們

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