java NIO系列教程(八)

來源:互聯網
上載者:User

轉載自並發編程網 – ifeve.com本文連結地址: Java NIO系列教程(八) SocketChannel

Java NIO中的SocketChannel是一個串連到TCP網路通訊端的通道。可以通過以下2種方式建立SocketChannel: 開啟一個SocketChannel並串連到互連網上的某台伺服器。 一個新串連到達ServerSocketChannel時,會建立一個SocketChannel。

開啟 SocketChannel

下面是SocketChannel的開啟檔案:

1 SocketChannel socketChannel = SocketChannel.open();
2 socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
關閉 SocketChannel

當用完SocketChannel之後調用SocketChannel.close()關閉SocketChannel:

1 socketChannel.close();
從 SocketChannel 讀取資料

要從SocketChannel中讀取資料,調用一個read()的方法之一。以下是例子:

1 ByteBuffer buf = ByteBuffer.allocate(48);
2 int bytesRead = socketChannel.read(buf);

首先,分配一個Buffer。從SocketChannel讀取到的資料將會放到這個Buffer中。

然後,調用SocketChannel.read()。該方法將資料從SocketChannel 讀到Buffer中。read()方法返回的int值表示讀了多少位元組進Buffer裡。如果返回的是-1,表示已經讀到了流的末尾(串連關閉了)。 寫入 SocketChannel

寫資料到SocketChannel用的是SocketChannel.write()方法,該方法以一個Buffer作為參數。樣本如下:

01 String newData = "New String to write to file..." + System.currentTimeMillis();
02  
03 ByteBuffer buf = ByteBuffer.allocate(48);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.