java中nio使用案例
时间: 2024-02-11 10:09:42 浏览: 47
Java NIO (New IO) 是Java SE 1.4引入的一个新的IO API,可以用来替代Java标准IO和Java网络编程中的Socket和ServerSocket。Java NIO提供了非阻塞式的IO操作,可以实现更高效的网络编程。
以下是Java NIO的一个使用案例:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class NIOServer {
public static void main(String[] args) throws IOException {
// 创建ServerSocketChannel并绑定端口
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
System.out.println("NIOServer started on port 9999");
// 创建一个ByteBuffer用于读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
// 接收客户端连接
SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel != null) {
System.out.println("Client connected from " + socketChannel.getRemoteAddress());
// 读取客户端发送的数据
int bytesRead = socketChannel.read(buffer);
while (bytesRead != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
bytesRead = socketChannel.read(buffer);
}
socketChannel.close();
}
// 处理控制台输入
Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();
if (message.equals("quit")) {
break;
}
}
// 关闭ServerSocketChannel
serverSocketChannel.close();
}
}
```
该程序实现了一个简单的NIO服务器,它监听9999端口,接收客户端连接并读取客户端发送的数据。程序通过一个无限循环来保持运行,可以通过控制台输入"quit"来退出程序。在程序运行过程中,可以使用telnet命令来模拟客户端连接并发送数据:
```
telnet localhost 9999
```
输入数据后,按下Enter键,然后可以在服务器控制台上看到客户端发送的数据。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)