天天看點

NIO邊看邊記 之 SocketChannel(八)

SocketChannel是一個連接配接到TCP的網絡套接字通道。建立SocketChannel有兩種方式:

a.打開一個SocketChannel并連接配接到一台網絡伺服器

b.一個新連接配接到達ServerSocketChannel時,會建立一個SocketChannel

1.打開

SocketChannel socketChannel = SocketChannel.open();

socketChannel.connect(new InetSocketAddress(“localhost”, 80));

2.關閉、讀、寫方式跟FileChannel都一樣

3.非阻塞模式

SocketChannel可以工作在非阻塞模式下,預設的工作模式時阻塞的。

設定方式:

SocketChannel.configureBlocking(false);
           

(1)connect

在非阻塞模式下,connect方法會立即傳回,為保證連接配接建立,需要調用finishConnect方法。

socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost", ));
while(! socketChannel.finishConnect() ){
    //wait, or do something else...
}
           

(2)非阻塞模式通常跟Selector聯合使用。