Original link Jakob Jenkov Translator: Zheng Yuting proofreading: Ding
The Serversocketchannel in Java NiO is a channel that can listen for incoming TCP connections, just like serversocket in standard IO. The Serversocketchannel class is in the Java.nio.channels package.
Here's an example:
01 |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
03 |
serverSocketChannel.socket().bind( new InetSocketAddress( 9999 )); |
06 |
SocketChannel socketChannel = |
07 |
serverSocketChannel.accept(); |
09 |
//do something with socketChannel... |
Open Serversocketchannel
Open the Serversocketchannel by calling the Serversocketchannel.open () method. For example:
1 |
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); |
Close Serversocketchannel
Close Serversocketchannel by calling the Serversocketchannel.close () method. Such as:
1 |
serverSocketChannel.close(); |
Listening for new Incoming connections
The new incoming connection is monitored by the serversocketchannel.accept () method. When the Accept () method returns, it returns a Socketchannel that contains the new incoming connection. Therefore, the accept () method is blocked until a new connection arrives.
Typically, you will not just listen to one connection, but call the Accept () method in the while loop. As in the following example:
2 |
SocketChannel socketChannel = |
3 |
serverSocketChannel.accept(); |
5 |
//do something with socketChannel... |
Of course, you can also use exit criteria other than true in the while loop.
Non-blocking mode
Serversocketchannel can be set to non-blocking mode. In nonblocking mode, the Accept () method returns immediately, or null if no new incoming connection has been entered. Therefore, you need to check if the returned Socketchannel is 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... |
original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java NiO Series Tutorial (ix) Serversocketchannel
Java NiO Series Tutorial (ix) Serversocketchannel