ServerSocketChannel 可以监听传入的TCP连接,与Java标准库的ServerSocket类似。

举个例子:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));

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

打开 ServerSocketChannel

通过调用ServerSocketChannel.open()方法来打开ServerSocketChannel

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

关闭 ServerSocketChannel

ServerSocketChannel.close()

监听 传入连接

通过调用ServerSocketChannel.accept()方法来监听传入连接。当accept()方法返回结果时,返回的是一个有传入连接的SocketChannel,因此此方法是阻塞的,会一直阻塞直到有连接传入。
一般循环调用此方法:

while(true){
    SocketChannel socketChannel = serverSocketChannel.accept();
		// todo
}

别忘了跳出循环…

非阻塞模式

ServerSocketChannel 也是可以被置为非阻塞模式的。在非阻塞模式下,accept()会立即返回,因此如果没有传入连接时可能返回null。所以需要检测是否返回的是null。

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...
    }
}

参考

  1. Java NIO ServerSocketChannel