Java NIO中的 ServerSocketChannel 是一個能夠監聽新進來的TCP鏈接的通道, 就像標準IO中的ServerSocket同樣。ServerSocketChannel類在 java.nio.channels包中。java
這裏有個例子:socket
查看源代碼 打印幫助spa
01 |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
03 |
serverSocketChannel.socket().bind( new InetSocketAddress( 9999 )); |
06 |
SocketChannel socketChannel = |
07 |
serverSocketChannel.accept(); |
09 |
//do something with socketChannel... |
打開 ServerSocketChannel
經過調用 ServerSocketChannel.open() 方法來打開ServerSocketChannel.如:code
查看源代碼 打印幫助server
1 |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
關閉 ServerSocketChannel
經過調用ServerSocketChannel.close() 方法來關閉ServerSocketChannel. 如:get
查看源代碼 打印幫助it
1 |
serverSocketChannel.close(); |
監聽新進來的鏈接
經過 ServerSocketChannel.accept() 方法監聽新進來的鏈接。當 accept()方法返回的時候,它返回一個包含新進來的鏈接的 SocketChannel。所以, accept()方法會一直阻塞到有新鏈接到達。io
一般不會僅僅只監聽一個鏈接,在while循環中調用 accept()方法. 以下面的例子:table
查看源代碼 打印幫助循環
2 |
SocketChannel socketChannel = |
3 |
serverSocketChannel.accept(); |
5 |
//do something with socketChannel... |
固然,也能夠在while循環中使用除了true之外的其它退出準則。
非阻塞模式
ServerSocketChannel能夠設置成非阻塞模式。在非阻塞模式下,accept() 方法會馬上返回,若是尚未新進來的鏈接,返回的將是null。 所以,須要檢查返回的SocketChannel是不是null.如:
查看源代碼 打印幫助
01 |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
03 |
serverSocketChannel.socket().bind( new InetSocketAddress( 9999 )); |
04 |
serverSocketChannel.configureBlocking( false ); |
07 |
SocketChannel socketChannel = |
08 |
serverSocketChannel.accept(); |
10 |
if (socketChannel != null ){ |
11 |
//do something with socketChannel... |