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... }}复制代码