Channel就是一个通道,用于传输数据,两端分别是缓冲区和实体(文件或者套接字),通道的特点(也是NIO的特点):通道中的数据总是要先读到一个缓冲区,或者总是要从一个缓冲区中读入。
Channel的分类
1) FileChannel:从文件中读写数据
2) SocketChannel:通过TCP协议读写网络中的数据
3) ServerSocketChannel:在服务器端可以监听新进来的TCP连接,像WEB服务器那样,对每一个新进来的请求创建一个SocketChannel
4) DatagramChannel:通过UDP协议读写网络中的数据
上面众多的分类,是对应了不同的实体,这些通道包括了文件IO、TCP和UDP网络IO。
下面来看看Channel的源码:
public interface Channel extends Closeable { public boolean isOpen(); public void close() throws IOException; }
从这里我们可以看到,Channel接口只提供了关闭通道和检测通道是否打开这两个方法,剩下方法的都是由子接口和实现类来定义提供。
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAATcAAAClCAIAAAC2mS2ZAAAYJklEQVR4nO2d+1cUV57A6z+YX+YPmD1nTs7+Mpk5m2lC2D3unMyMOjoJrmkzitJUN4SHMAdN1BgjOT6QlwZaEgWV4bUgjUDbSEQcjZ6YkYiCyCMhK8JEUKOE1urm0d3gbu0P1V11q+pWdVXTTVc138+5J3bdunXr3uZ+uLeKqm8ICqG2tvZ63ygkSJA0lQiwFBIkjSe8pRQAABoALAUUce7cuaysLKN6srKyzp07F+3m6xuwFAiOzWazWCylpaVV6iktLd2yZYvNZot2J3RMaJa2kISh4G6k28aciGxRXvxugSHSDVvSKbT6vQUjMzPTarWePXv2C/VcunSptLQ0MzMzfM0JP9c7i4KmaDZPgaUtJBHA/6PX6mgDS7kThdNSo9FYV1fX1dXV09PT09Pzj8bfM6lHAb29vT09PUajUdUZ30pKVlhya3Xu78u3mmp3qu8Wx5cXi30LL2XSlxeLl1I/lixZ0JLBLG0hOTcpimohDQV39Tvaoo1evzej0djc3Pz1118PDAwMDAz8veKV//vfF3+veGVAAUNDQ4ODg6osfSspOXdPvhJRN53J3uXYWdddsNO+Y9OZ7SF38PKFY76Fl7a7l16vJG13L4ktvXzhWMiVy5C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AaB3Gx/8HlUsBPVQqimEAAAAASUVORK5CYII=" alt="" />
我们选择其中几个来看看这些接口的源码:
public interface WritableByteChannel
extends Channel
{ public int write(ByteBuffer src) throws IOException; }
public interface ReadableByteChannel extends Channel
{
public int read(ByteBuffer dst) throws IOException; }
public interface ByteChannel
extends ReadableByteChannel, WritableByteChannel
{ }
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAASUAAACRCAIAAAAKKTn3AAAUlklEQVR4nO2d+1dTV77A938wv8wfMPeuLtes1TWdWo2d5t7rndWZsd4+RkdTFRAa1DmA2IXOtFRRHNA0oGMxtSpPIVAe4TkocoDxwa2tVkakgihcUlTkoUAIARUCaPf94SQn552TcHJCzPezvst1srPP3jsn+8Pe5+ScLTKbzY5QoiNjlb7atV2tR2hVRofS5SO6ApncuXPHbDafvWrNPd/Jj6RkA7Xx/lfbdaejUiyJfzoV+f5X2wUzi0Z+8r8j3ceelIZNv0T/leZLCRDnO2uv9JnNZrPZfOfOHUW7jVxQqPlGGeFCadkci/Gt9kqftG+55zs3Zse9lbFhU85On3rJx2sRQhy7wDc/o7K1t7K1N1jKhaBvSw/Kt8rW3qB3JgiZUXbxblAGOvBNASjfyi7eDXo3gpAfxS3dxS3dZjfqiAe+KQDlW3FLd9D7EISvcYbsokId8ZAZUIgzZFfQew/E4iOgnQSZzeagf0IIiDAJ8A0CQr3w+Ba4OSsAABTgGwCoB/gGAOqhsm/VeqQxKn5PiHBFvtwl0mHUBLphi6piqR43wEdYvlXrkQcFvl9Gea4vcan2G/DNUxH4FhASEhISEhK4vtHfarUeiR/5DqPG29dSrUfMAqr1GmMH9Bt/geP2MiDlm6RSXn0TsxX6jX/AcXtJEPONNoo9DarWI41Gw51zeuaNngTh7lGtRxqjUc+eZFKVcNJYOd2FCSYKNcCf+aQ7P7cxrCPgeSHQZuGP6dqX9TeKOXMXbCfnEwXhuEl9PsBfZJy/MeRxfxvMviM0KEr55v76mD1Xz5/FCuYUS+SPyn77JtQYTw2MP0M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8BL4SSb4Fdv0RrsvrmGywlAvhMKN0/Gdj1S1h469CwlAjgF6H0fEDA1y/xIN2hYSkRwE9g/RLBBGaH5q3kAUuJAP4S/Oe7g7t+CevxNwHfhFbygKVEAH8Jvm946axfwvdNcCUPWEoE8Jfg+7aE1i8R9E14JQ9YSgTwB1i/RDCBOZ/kr+QBS4kAfhJK1ycplF2/xPv1EuF1XWEpEcAfQun3N5rQWL8EAHiE0v0lABDqgG8AoB7gGwCoB/gGAOoBvgGAeoBvAKAe4BsAqEdI+gbrlwAhSuj5BuuXAKFLiPkW2PVLfEPicVU/gGdVw4JQ8k3p9Usw8yZI3/vgYnyDtU/ClFC6f1Lp9Us4/x2pr71Qvm/8/0gV1j4JU0Lp+QCF1y9hPRHqB/75BmufhDXhvH6JRNfnzvY46fSTpKz/aNgzM+Q8i814DWufhDfBf747eOuX0L2RK5Wnv7JXHGGbwljORPi/26aFZJgJa5+EN8H3DQdt/RIXriGE/yCo+02RNYKsJi0iCPYYKbzciEzfYO2Tl5/g+xa89UuYuIcPAd/ELmdQiypotZzpm4BOnPM3WPskfAnj9UtYlyTpvsmbT3oWnfQ4Y2KOWoxlSUSWG2FdWYG1T8KZULo+SaHc+iWsBShFJoWMZE9uvkXULvTJmshVD+ZZHrcGWPskLAil399oYP0SIEQJpftLACDUAd8AQD3ANwBQD/ANANQDfAMA9QDfAEA9wDcAUA/wDQDUA3wDAPUA3wBAPcA3AFAP8A0A1AN8AwD1AN8AQD3ANwBQj/8HmSa6Wd3n4tQAAAAASUVORK5CYII=" alt="" />
前面我提到过:通道可以只读、只写或者同时读写,因为Channel类可以只实现只读接口ReadableByteChannel或者只实现只写接口WritableByteChannel,而我们常用的Channel类FileChannel、SocketChannel、DatagramChannel是双向通信的, 因为实现了ByteChannel接口。
Channel的获取
IO在广义上可以分为:文件IO和网络IO。文件IO对应的通道为FileChannel,而网络IO对应的通道则有三个:SocketChannel、ServerSoketChannel和DatagramChannel。
一、文件通道
FileChannel对象不能直接创建,只能通过FileInputStream、OutputStream、RandomAccessFile对象的getChannel()来获取,如:
FileInputStream fis = new FileInputStream("c:/in.txt");
FileChannel fic = fis.getChannel();
FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。
1)使用通道读取文件
public class NIOFileReadTest
{
public static void main(String[] args) throws IOException
{
RandomAccessFile raf = new RandomAccessFile("D:/in.txt","rw");
FileChannel fis = raf.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
fis.read(buffer);
buffer.flip();
while(buffer.hasRemaining())
{
System.out.print((char)buffer.get());
}
buffer.clear();
fis.close();
}
}
执行结果:
FileChannel
ByteBuffer
SelectorPicked
2)使用通道写入文件
public class NIOFileWriteTest
{
public static void main(String[] args) throws Exception
{
FileOutputStream fos = new FileOutputStream("d:/out.txt");
FileChannel fc = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.clear();
String str = "Channel";
buffer.put(str.getBytes());
buffer.flip();
while(buffer.hasRemaining())
{
fc.write(buffer);
}
fc.close();
fos.close();
}
}
在这里总是要记住channel是要关闭的。
ByteBuffer中的方法我在下一章再详细介绍,这里只要注意这点即可:通道只能使用ByteBuffer,不管是读还是写,通道都要对接缓冲区。
3)通道的常用方法
position();返回通道的文件位置
position(long newPosition):设置通道的文件位置
将上面读文件的程序修改下,来观察这几个方法:
public class NIOFileReadTest
{
public static void main(String[] args) throws IOException
{
RandomAccessFile raf = new RandomAccessFile("D:/in.txt","rw");
FileChannel fis = raf.getChannel();
System.out.println("此通道文件的总长度:" +fis.size());
//当前通道的文件位置
long position = fis.position();
System.out.println("通道当前的位置:" + position);
//设置新的通道文件位置,从这个位置开始读取
fis.position(position + 8);
ByteBuffer buffer = ByteBuffer.allocate(50);
fis.read(buffer);
buffer.flip();
while(buffer.hasRemaining())
{
System.out.print((char)buffer.get());
}
buffer.clear();
fis.close();
}
}
执行结果:
此通道文件的总长度:33
通道当前的位置:0
nel
ByteBuffer
Selector
FileChannel是线程安全的,可以多个线程在同一个实例上并发操作,但是其中有些方法(改变文件通道位置或者文件大小的方法)必须是单线程操作。
二、网络通道
SocketChannel是一个连接到TCP套接字的通道,获取的方式有两种:
1、打开一个SocketChannel并连接到互联网上某台服务器。
2、一个新连接到达ServerSocketChannel时,会创建一个SocketChannel。
上面这两种模式跟IO的Socket、ServerSocket类似,下面分别来看看客户端和服务器端:
一、SocketChannel
从通道中读取数据
public class SocketChannelTest
{
public static void main(String[] args) throws Exception
{
//获取socket通道
SocketChannel sc = SocketChannel.open();
//设置为非阻塞模式
sc.configureBlocking(false);
//建立连接,非阻塞模式下,该方法可能在连接建立之前就返回了
sc.connect(new InetSocketAddress("wap.cmread.com",80));
//判断连接是否建立
while(!sc.finishConnect())
{
System.out.println("连接未建立");
Thread.sleep(5);
}
ByteBuffer buffer = ByteBuffer.allocate(48);
int byteRead = sc.read(buffer);
System.out.println(byteRead);
sc.close();
buffer.clear();
}
}
执行结果;
连接未建立
连接未建立
0
1、第6、7行是获取一个socket通道,并且设置为非阻塞模式。
2、由于是非阻塞模式,通道在调用方法connect/read/writer这三个方法时,会出现这些情况:连接未建立,connect方法就返回了;尚未读取任何数据时,read方法就返回;尚未写出任何内容时,writer就返回。
3、在12行的循环代码中,是判断连接是否建立,从执行结果来看,循环执行了两次连接才建立(在循环里线程还有休眠)。
4、由于只是建立了连接,通道里面其实没有任何的数据。
5、第18行调用read方法,由于是非阻塞模式,所以在并未读取任何数据的情况下就返回0(尽管通道里面没有数据)。
将数据写入通道
public class SocketChannelTest
{
public static void main(String[] args) throws Exception
{
SocketChannel sc = SocketChannel.open();
String str = "non-blocking socket channel";
ByteBuffer buffer = ByteBuffer.allocate(100);
buffer.put(str.getBytes());
buffer.flip();
while(buffer.hasRemaining())
{
sc.write(buffer);
}
sc.close();
buffer.clear();
}
}
1、SocketChannel.write()方法的调用是在一个while循环中的。Write()方法无法保证能写多少字节到SocketChannel。所以,我们重复调用write()直到Buffer没有要写的字节为止。
二、ServerSocketChannel
ServerSocketChannel是一个可以监听新进来的TCP连接的通道。
public class ServerSocketChannelTest
{
public static void main(String[] args) throws Exception
{
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(80));
ssc.configureBlocking(false);
while(true)
{
SocketChannel sc = ssc.accept();
if(null != sc)
{
//do something;
}
}
}
}
1、第5、6、7行,获取一个ServerSocketChannel,并且监听80端口,设置为非阻塞模式。
2、通过accept方法监听新接入进来的连接,这个方法会返回一个包含新进来的连接的SocketChannel(服务器端的通道的获取方式)。如果是阻塞模式,该方法会一直阻塞直到有新的连接进来。如果是非阻塞模式,则accept方法会立刻返回,返回值是null。
3、第11行,是因为在非阻塞模式下,需要检查SocketChannel是否为null。
三、socket通道与socket
ServerSocketChannel ssc = ServerSocketChannel.open();
ServerSocket socket = ssc.socket();
ServerSocketChannel ssc1 = socket.getChannel();
1、从这代码片段可以大概看到这样一种关系:所有socket通道(SocketChannel/ServerSocketChanne/DatagramSocketChannel)在被实例化之后,都是伴随生成对应的socket对象,就是前面IO章节介绍的java.net类(Socket/ServerSocket/DatagramSocket)。通过通道类的socket方法来获取。
2、java.net类(Socket/ServerSocket/DatagramSocket)现在可以通过getChannel方法来获取对应的通道。前提是这些socket对象不是使用传统方式(直接实例化)创建的。否则它就没有关联的socket通道,调用getChannel方法返回总是null。