Java NIO ServerSocketChannel是一個監聽TCP連線的Channel,如Java 標準網路中的ServerSocket。ServerSocketChannel類是在java.nio.channels包下。
下面是一個例子:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket.bind(new InetAddress(9990));
while(true){
SocketChannel socketChannel = serverSocketChannle.accept();
// do something with socketChannel
}
複製程式碼
Opening a ServerSocketChannel
可以通過ServerSocketChannel的open方法來開啟ServerSocketChannel。如下所示:
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
複製程式碼
Closing a ServerSocketChannel
關閉ServerSocketChannel可以通過ServerSocketChannel的close()方法來實現。如下所示: serverSocketChannel.close();
Listening for Incoming Connections
可以通過ServerSocketChannel的accept()來監聽新進來的連線。當accept()方法返回時,它將返回SocketChannel物件。因此,accept()方法會阻塞直接有新的連線進來。
通常不會僅僅只監聽一個連線,在while迴圈中呼叫 accept()方法. 如下面的例子:
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
//do something with socketChannel...
}
複製程式碼
當然也可以在while迴圈中使用除了true以外的其他條件。
Non-blocking Mode
一個ServerSocketChannel可以被設定工作在非阻塞模式。在非阻塞模式中,accept()方法會立即返回。因此它可能會返回null如果沒有新的連線進來。因此,你必須檢查返回的SocketChannel物件是否為null。
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9990));
serverSocketChannel.configureBlocking(false);
while(true){
SocketChannel socketChannel = serverSocketChannel.accept();
if(seocketChannle != null){
// do something with socketChannel...
}
}
複製程式碼