Java NIO中的SocketChannel是一個鏈接到TCP網絡套接字的通道。能夠經過如下2種方式建立SocketChannel:服務器
1.打開一個SocketChannel並鏈接到互聯網上的某臺服務器。 2.一個新鏈接到達ServerSocketChannel時,會建立一個SocketChannel。
打開 SocketChannel
下面是SocketChannel的打開方式:網絡
SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80)); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); ServerSocket ss = serverSocketChannel.socket(); ss.bind(new InetSocketAddress("localhost", 9026));// 綁定地址
關閉 SocketChannel異步
當用完SocketChannel以後調用SocketChannel.close()關閉SocketChannel:socket
socketChannel.close();
從 SocketChannel 讀取數據code
要從SocketChannel中讀取數據,調用一個read()的方法之一。如下是例子:server
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = socketChannel.read(buf);
首先,分配一個Buffer。從SocketChannel讀取到的數據將會放到這個Buffer中。ip
而後,調用SocketChannel.read()。該方法將數據從SocketChannel 讀到Buffer中。get
read()方法返回的int值表示讀了多少字節進Buffer裏。it
若是返回的是-1,表示已經讀到了流的末尾(鏈接關閉了)。file
寫入 SocketChannel
寫數據到SocketChannel用的是SocketChannel.write()方法,該方法以一個Buffer做爲參數。示例以下:
String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { channel.write(buf); }
注意SocketChannel.write()方法的調用是在一個while循環中的。Write()方法沒法保證能寫多少字節到SocketChannel。因此,咱們重複調用write()直到Buffer沒有要寫的字節爲止。
非阻塞模式
能夠設置 SocketChannel 爲非阻塞模式(non-blocking mode).設置以後,就能夠在異步模式下調用connect(), read() 和write()了。
connect()
若是SocketChannel在非阻塞模式下,此時調用connect(),該方法可能在鏈接創建以前就返回了。爲了肯定鏈接是否創建,能夠調用finishConnect()的方法。像這樣:
socketChannel.configureBlocking(false);//非阻塞 socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80)); while(! socketChannel.finishConnect() ){ //wait, or do something else... }
write()
非阻塞模式下,write()方法在還沒有寫出任何內容時可能就返回了。因此須要在循環中調用write()。
read()
非阻塞模式下,read()方法在還沒有讀取到任何數據時可能就返回了。因此須要關注它的int返回值,它會告訴你讀取了多少字節。
非阻塞模式與選擇器非阻塞模式與選擇器搭配會工做的更好,經過將一或多個SocketChannel註冊到Selector,能夠詢問選擇器哪一個通道已經準備好了讀取,寫入等。