Java NIO-9.ServerSocketChannel

Java NIO ServerSocketChannel是一个能够监听新进TCP连接的通道,就像标准Java网络连接中的ServerSocket。ServerSocketChannel类在java.nio.channels包中。
一个例子:

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,例如

serverSocketChannel.close();

监听新进连接

监听新进连接是通过调用ServerSocketChannel.accept()方法实现的。accept()方法返回一个带有新进连接的SocketChannel。因此accept()方法在新进连接到达之前一直处于阻塞状态。
通常不会只监听单个连接,而是在while循环中调用accept()方法:

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

    //do something with socketChannel...
}

当然,也可以在while循环中使用除了true意外的其他退出准则。

非阻塞模式

ServerSocketChannel可以设置为非阻塞模式,此时accept立即返回,没有新进连接到达就返回空。因此需要检查返回的SocketChannel是否为空,例如:

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

你可能感兴趣的:(Java NIO-9.ServerSocketChannel)