Java NIO系列教程(八) SocketChannel

Java NIO系列教程(八) SocketChannel

Java NIO 中的 SocketChannel 是一个链接到 TCP 网络套接字的通道。能够经过如下 2 种方式建立 SocketChannel:java

  • 打开一个 SocketChannel 并链接到互联网上的某台服务器。
  • 一个新链接到达 ServerSocketChannel 时,会建立一个 SocketChannel。

1、打开 SocketChannel

下面是 SocketChannel 的打开方式:编程

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

2、关闭 SocketChannel

当用完 SocketChannel 以后调用 SocketChannel.close() 关闭 SocketChannel:服务器

SocketChannel.close();

3、从 SocketChannel 读取数据

要从 SocketChannel 中读取数据,调用一个 read() 的方法之一。如下是例子:网络

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

首先,分配一个 Buffer。从 SocketChannel 读取到的数据将会放到这个 Buffer 中。并发

而后,调用 SocketChannel.read()。该方法将数据从 SocketChannel 读到 Buffer 中。read() 方法返回的 int 值表示读了多少字节进 Buffer 里。若是返回的是 -1,表示已经读到了流的末尾(链接关闭了)。异步

4、写入 SocketChannel

写数据到 SocketChannel 用的是 SocketChannel.write() 方法,该方法以一个 Buffer 做为参数。示例以下:socket

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 没有要写的字节为止。code

5、非阻塞模式

能够设置 SocketChannel 为非阻塞模式(non-blocking mode).设置以后,就能够在异步模式下调用 connect(), read() 和 write() 了。教程

(1) connect()ip

若是 SocketChannel 在非阻塞模式下,此时调用 connect() ,该方法可能在链接创建以前就返回了。为了肯定链接是否创建,能够调用 finishConnect() 的方法。像这样:

socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
 
while(! socketChannel.finishConnect() ){
    //wait, or do something else...
}

(2) write()

非阻塞模式下,write() 方法在还没有写出任何内容时可能就返回了。因此须要在循环中调用 write()。前面已经有例子了,这里就不赘述了。

(3) read()

非阻塞模式下,read() 方法在还没有读取到任何数据时可能就返回了。因此须要关注它的 int 返回值,它会告诉你读取了多少字节。

6、非阻塞模式与选择器

非阻塞模式与选择器搭配会工做的更好,经过将一或多个 SocketChannel 注册到 Selector,能够询问选择器哪一个通道已经准备好了读取,写入等。Selector 与 SocketChannel 的搭配使用会在后面详讲。

转载自并发编程网 – ifeve.com,本文连接地址: Java NIO系列教程(八) SocketChannel

相关文章
相关标签/搜索