Channel
-
java Nio Channel
通常来说,所有的NIO的I/O操作都是从Channel开始的。一个channel类似于一个stoream.java Stream和NIO Channel对比
(1)我们可以在同一个Channel中执行读和写操作,然而同一个Stream仅仅支持读或写;
(2)Channel可以异步地读写,而Stream是阻塞的同步读写;
(3)Channel总是从Buffer中读取数据,或将数据写入到Buffer中。 -
Channel类型有:
(1)FileChannel,文件操作
(2)DatagramChannel,UDP操作
(3)SocketChannel,TCP操作
(4)ServerSocketChannel ,TCP操作,使用在服务器端。
这些通道涵盖了UDP和TCP网络IO以及文件IO。 -
FileChannel
java nio中的FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。
FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。
(1)打开FileChannel
在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。下面是通过RandomAccessFile打开FileChannel的实例:RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();
(2)从FileChannel读取数据
调用多个read()方法之一,从FileChannel中读取数据,如下:ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = inChannel.read(but);
首先,分配一个Buffer。从FileChannel中读取的数据将被读到Buffer中。然后调用FileChannel.read()方法。该方法将数据从FIleChannel读取到Buffer中。read()方法返回的int值表示了有多少自己被读到了Buffer中。如果返回-1,表示到了文件末尾。
(3)向FileChannel写数据
使用FileChannel.write()方法向FileChannel写数据,该方法的参数是一个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);
}
FileChannel.write()是在while循环中调用的。因为无法保证write()方法一次能向FileChannel写入多少字节,因此需要重复调用write()方法,知道Buffer总已经没有尚未写入通道的字节。
(4)关闭FileChannel
用完FileChannel后必须将其关闭,如:
channel.close();
(5)FileChannel的position方法
有时候可能需要在FileChannel的某个特定位置进行 数据的读/写操作。可以通过调用position()方法获取FileChannel的当前位置。也可以通过position(long pos)方法设置FileChannel的当前位置。
long pos = channel.position();
channel.position(pos +123);
如果将位置设置在文件结束符之后,那么试图从文件通道中读取数据,读方法将返回-1-----》文件结束标志。
如果将位置设置在文件结束符之后,然后向通道中写数据,文件将撑大到当前位置并写入数据。这可能导致“文件空洞”,磁盘上物理文件中写入的数据间有空隙。
(6)FileChannel的size方法
FileChannel实例的size()方法将返回该实例所关联文件的大小。
(7)FileChannel的truncate方法
可以使用FileChannel.truncate()方法截取一个文件。截取文件时,文件将指定长度后面的部分删除
channel.truncate(1024);
这个例子截取文件的前1024个字节。
(8)FileChannel的force方法
FileChannel.force()方法将通道里尚未写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操作系统会将数据缓存在内存中,所以无法保证写入到FileChannel里的数据一定会及时写到磁盘上。要保证这一点,需要调用force方法。force()方法有个boolean类型的番薯,指明是否同时将文件元数据(权限信息等)写到磁盘上。
channel.force(true);
-
SocketChannel
SocketChannel是一个客户端用来进行TCP连接的Channel.
创建一个SocketChannel的方法有两种:
1.打开一个SocketChannel,然后将其连接到某个服务器中
2.当一个ServerSocketChannel接受到连接请求时,会返回一个SocketChannel对象。
(1) 打开SocketChannelSocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("http://example.com", 80));
(2) 关闭
socketChannel.close();
(3)读取数据
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(but);
如果read()返回-1,那么表示连接中断了
(4)写入数据
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);
}
(5) 非阻塞模式
可以设置SocketChannel为异步模式,这样我们的connect,read,write都是异步的了。
连接
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://example.com", 80));
while(! socketChannel.finishConnect() ){
//wait, or do something else...
}
在异步模式中,或许连接还没有建立,connect()就返回了,因此我们需要检查当前是否连接到了主机,因此通过一个while循环来判断
(6) 读写
在异步模式下,读写的方式是一样的,在读取时,因为是异步的,因此我们必须检查read的返回值,来判断当前是否读取到了数据。
-
ServerSocketChannel
ServerSocketChannel顾名思义,使用在服务端的,可以监听客户端的TCP连接,例如:ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); //do something with socketChannel... }
(1) 打开关闭
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.close();
(2) 监听连接
我们可以使用ServerSocketChannel.accept()方法来监听客户端的TCP连接请求,accept()方法会阻塞,知道有连接到来,当有连接时,这个方法会返回一个SocketChannel对象
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
//do something with socketChannel...
}
(3)非阻塞模式
在非阻塞模式下,accept()是非阻塞的,因此如果此时没有连接到来,那么accept()方法会返回null
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
while(true){
SocketChannel socketChannel =
serverSocketChannel.accept();
if(socketChannel != null){
//do something with socketChannel...
}
}
-
DatagramChannel
DatagramChannel是用来处理UDP连接的。
(1)打开DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999));
(2)读取数据
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
channel.receive(but);
(3)发送数据
String newData = "New String to write to file..."
+ System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
int bytesSent = channel.send(buf, new InetSocketAddress("example.com", 80));
(4)连接到指定地址
因为UPD是非连接的,因此这个connect并不是像TCP一样真正意义上的连接,而是他会将DatagramChannel锁住,因此我们仅仅可以从指定的地址中读取或写入数据
channel.connect(new InetSocketAddress("example.com", 80));