高并发IO底层原理浅析(二)

在Java NIO中,Channel是用于进行数据读写的基础组件,它是连接到能够执行I/O操作的实体(如文件、套接字)的对象。Channel类似于传统IO中的InputStream和OutputStream,但与之不同的是,Channel是双向的,可以同时用于读取和写出数据,并且通常配合Buffer对象使用以提高效率。

以下是一个关于Java NIO Channel的几个具体实现类及其用途的详细举例:

1.FileChannel

通过java.nio.channels.FileChannel类,可以高效地读写文件。例如:

java 复制代码
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
FileChannel channel = raf.getChannel();

// 写入数据到文件
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello, World!".getBytes());
buffer.flip(); // 准备从buffer读取数据
channel.write(buffer);

// 从文件读取数据
buffer.clear();
int bytesRead = channel.read(buffer);
buffer.flip();
while (buffer.hasRemaining()) {
    System.out.print((char) buffer.get());
}

2.SocketChannel:

  • java.nio.channels.SocketChannel用于网络通信,提供TCP/IP协议的客户端和服务端连接。例如创建一个TCP客户端连接:
java 复制代码
SocketChannel clientChannel = SocketChannel.open(new InetSocketAddress(host, port));
clientChannel.configureBlocking(false); // 设置为非阻塞模式

// 缓冲区准备发送数据
ByteBuffer outputBuffer = ByteBuffer.wrap(message.getBytes());

// 发送数据
while (outputBuffer.hasRemaining()) {
    clientChannel.write(outputBuffer);
}

// 接收服务器响应
ByteBuffer inputBuffer = ByteBuffer.allocate(1024);
while (clientChannel.read(inputBuffer) > 0) {
    inputBuffer.flip();
    byte[] data = new byte[inputBuffer.remaining()];
    inputBuffer.get(data);
    String response = new String(data, StandardCharsets.UTF_8);
    System.out.println("Server responded: " + response);
    inputBuffer.clear();
}

3.DatagramChannel:

  • java.nio.channels.DatagramChannel用于UDP通信,处理无连接的数据报包。
java 复制代码
DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(port));

// 接收数据报
ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
SocketAddress sender = channel.receive(receiveBuffer);
receiveBuffer.flip();
byte[] data = new byte[receiveBuffer.remaining()];
receiveBuffer.get(data);
System.out.println("Received from: " + sender + ", Data: " + new String(data));

// 发送数据报
ByteBuffer sendBuffer = ByteBuffer.wrap(message.getBytes());
channel.send(sendBuffer, new InetSocketAddress(remoteHost, remotePort));

4.ServerSocketChannel:

  • java.nio.channels.ServerSocketChannel用于监听新的TCP连接请求,建立SocketChannel来服务每个新连接
java 复制代码
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false); // 非阻塞模式

while (true) {
    SocketChannel socketChannel = serverSocketChannel.accept();
    if (socketChannel != null) {
        // 创建线程或使用Selector处理新连接
        handleClientConnection(socketChannel);
    }
}

以上示例展示了如何创建并使用不同类型的Channel进行I/O操作,实际场景中往往还会结合Selector来进行高效的多路复用,从而在一个单线程中处理多个Channel上的事件。

相关推荐
Wyc724095 分钟前
Maven
java·数据库·maven
程序猿小D8 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
吴free35 分钟前
mac电脑wireshark快速实现http接口抓包
网络·测试工具·http·wireshark
艾希逐月1 小时前
TCP数据的发送和接收
服务器·网络·tcp/ip
木头没有瓜1 小时前
idea离线安装插件
java·ide·intellij-idea
llwszx2 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
述雾学java2 小时前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel
保持学习ing2 小时前
苍穹外卖day3--公共字段填充+新增菜品
java·阿里云·实战·springboot·前后端·外卖项目·阿里云文件存储
77qqqiqi2 小时前
正则表达式
java·后端·正则表达式
厦门德仔3 小时前
【WPF】WPF(样式)
android·java·wpf