Java NIO ServerSocketChannel

Java NIO ServerSocketChannel是一个监听传入的TCP连接的通道,就像标准Java Networking中的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...

}


1.打开一个ServerSocketChannel

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

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();


2.关闭ServerSocketChannel

通过调用ServerSocketChannel.close()方法来关闭ServerSocketChannel:

serverSocketChannel.close();


3.监听连接

通过调用ServerSocketChannel.accept()方法来监听连接。当accept()方法返回时,它将返回连接的SocketChannel。因此,accept()方法将阻塞,直到传入连接到达为止。

通常不会仅监听一个连接,因此可以在while循环内调用accept():

while(true){

    SocketChannel socketChannel =

            serverSocketChannel.accept();



    //do something with socketChannel...

}


4.非阻塞模式

可以将ServerSocketChannel设置为非阻塞模式,在非阻塞模式下,accept()方法立即返回,如果没有连接到达,则返回null。因此,必须检查返回的SocketChannel是否为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...

        }

}



 

展开阅读全文