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,能够询问选择器哪一个通道已经准备好了读取,写入等。