在Java NIO中,ServerSocketChannel是用於監聽TCP連接請求的通道,正如Java網絡編程中的ServerSocket同樣。java
ServerSocketChannel實現類位於java.nio.channels包下面。 下面是一個示例程序:編程
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bin(new InetSocketAddress(9999)); while(true) { SocketChannel socketChannel = serverSocketChannel.accept(); //do something with socketChannel... }
打開一個ServerSocketChannel咱們須要調用他的open()方法,例如:網絡
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
關閉一個ServerSocketChannel咱們須要調用他的close()方法,例如:socket
serverSocketChannel.close();
經過調用accept()方法,咱們就開始監聽端口上的請求鏈接。當accept()返回時,他會返回一個SocketChannel鏈接實例,實際上accept()是阻塞操做,他會阻塞帶去線程知道返回一個鏈接; 不少時候咱們是不知足於監聽一個鏈接的,所以咱們會把accept()的調用放到循環中,就像這樣:函數
while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); //do something with socketChannel... }
固然咱們能夠在循環體內加上合適的中斷邏輯,而不是單純的在while循環中寫true,以此來結束循環監聽;spa
實際上ServerSocketChannel是能夠設置爲非阻塞模式的。在非阻塞模式下,調用accept()函數會馬上返回,若是當前沒有請求的連接,那麼返回值爲空null。所以咱們須要手動檢查返回的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... } }