nio的read write方法在为配置configBlocking时使用是阻塞还是不阻塞
时间: 2024-04-09 19:28:00 浏览: 18
在Java NIO中,`read()`和`write()`方法的塞行为取决于通道的阻塞式。当通道配置为阻塞模式,这些方法将会阻塞,直到读取或写入操作完成。而当通道为非阻塞模式时,这些方法会立即返回,无论读取或写入是否完成。
要配置通道的阻塞模式,可以使用`configureBlocking(boolean block)`方法。将参数`block`设置为`true`即可将通道设置为阻塞模式,设置为`false`则为非阻塞模式。
下面是一个示例:
```java
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(true); // 阻塞模式
int bytesRead = channel.read(buffer); // 阻塞直到数据读取完成
int bytesWritten = channel.write(buffer); // 阻塞直到数据写入完成
```
需要注意的是,默认情况下,通道是阻塞模式。因此,如果没有显式地调用`configureBlocking()`方法将其设置为非阻塞模式,那么`read()`和`write()`方法将默认为阻塞模式。
相关问题
使用Java NIO写一个异步非阻塞接口,功能是把指定文件地址的文件返回给前端
以下是一个简单的使用Java NIO实现异步非阻塞接口的示例,可以根据实际需求进行修改:
```java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class AsyncFileServer {
private static final int PORT_NUMBER = 8000;
private static final int BUFFER_SIZE = 1024;
private static final long TIMEOUT = 30; // seconds
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT_NUMBER), 0);
server.createContext("/file", new FileHandler());
server.start();
System.out.println("Server started on port " + PORT_NUMBER);
}
private static class FileHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String filePath = exchange.getRequestURI().getPath().substring("/file/".length());
Path path = Paths.get(filePath);
try {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path);
CountDownLatch latch = new CountDownLatch(1);
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
if (result == -1) {
try {
exchange.sendResponseHeaders(404, -1);
} catch (IOException e) {
e.printStackTrace();
}
} else if (result < BUFFER_SIZE) {
attachment.limit(result);
try {
exchange.sendResponseHeaders(200, result);
exchange.getResponseBody().write(attachment.array());
} catch (IOException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
} else {
try {
exchange.sendResponseHeaders(200, result);
exchange.getResponseBody().write(attachment.array());
attachment.clear();
fileChannel.read(attachment, result, attachment, this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
exc.printStackTrace();
try {
exchange.sendResponseHeaders(500, -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
});
if (!latch.await(TIMEOUT, TimeUnit.SECONDS)) {
exchange.sendResponseHeaders(500, -1);
}
exchange.close();
} catch (IOException | InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
exchange.sendResponseHeaders(500, -1);
exchange.close();
}
}
}
}
```
这个示例中,我们创建了一个`HttpServer`实例,并使用`createContext()`方法将`/file`路径映射到`FileHandler`处理器类上。在`FileHandler`类的`handle()`方法中,我们首先获取请求中指定的文件路径,并使用`AsynchronousFileChannel`打开该文件。然后,我们创建一个`CountDownLatch`实例,用于等待异步读取操作完成。我们还创建了一个`ByteBuffer`实例,用于缓存读取的数据。
接下来,我们调用`read()`方法,传入`buffer`和一个`CompletionHandler`实例作为参数。`CompletionHandler`是一个回调接口,用于在异步操作完成时被调用。在我们的实现中,我们在`completed()`方法中判断读取的结果。如果返回值为-1,则表示文件不存在,我们发送404响应码。如果返回值小于缓冲区大小,则说明读取已经完成,我们发送200响应码,并将读取的数据写入响应体中。如果返回值等于缓冲区大小,则说明还有更多的数据需要读取,我们继续调用`read()`方法,传入一个新的`ByteBuffer`实例,并在回调中递归调用自己。
在`failed()`方法中,我们处理异步操作失败的情况。我们打印异常栈轨迹,并发送500响应码。
最后,我们使用`await()`方法等待异步操作完成,如果超时则发送500响应码。最后,我们关闭`HttpExchange`实例,结束请求处理。
nio channel方法
Java NIO中的Channel是用于在Java程序中进行I/O操作的基本组件之一。Channel提供了一种高效的、可扩展的方式来进行数据传输,同时也支持非阻塞式I/O操作。
下面是一些常用的Channel方法:
1. `open()`:打开一个新的Channel对象。
2. `close()`:关闭当前的Channel对象。
3. `read(ByteBuffer dst)`:从Channel中读取数据到指定的ByteBuffer中。
4. `write(ByteBuffer src)`:将数据从指定的ByteBuffer写入到Channel中。
5. `configureBlocking(boolean block)`:设置当前Channel的阻塞模式,如果为true则为阻塞模式,如果为false则为非阻塞模式。
6. `register(Selector sel, int ops)`:将当前的Channel对象注册到指定的Selector中,并且指定关注的事件类型。
7. `isOpen()`:判断当前的Channel对象是否处于打开状态。
8. `isConnected()`:判断当前的Channel对象是否已经连接到远程服务器。
9. `finishConnect()`:完成Channel对象的连接操作,如果连接成功则返回true,否则返回false。
10. `bind(SocketAddress local)`:将当前的Channel对象绑定到指定的本地地址。
11. `getRemoteAddress()`:获取当前Channel对象连接的远程服务器地址。
12. `getLocalAddress()`:获取当前Channel对象绑定的本地服务器地址。
这些方法提供了基本的Channel操作,可以根据具体的需求进行使用。需要注意的是,Channel对象在使用完毕后需要调用close()方法进行关闭,否则可能会出现资源泄漏等问题。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)