Java,Java NIO,Java NIO2,Java AIO,AsynchronousServerSocketChannel

Server.java

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousServerSocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author Bright Lee */ public final class Server { private final Configuration configuration; private final ExecutorService pool; private final AsynchronousChannelGroup group; private final AsynchronousServerSocketChannel serverChannel; public Server() { configuration = new Configuration(); try { pool = Executors.newFixedThreadPool (4); group = AsynchronousChannelGroup.withThreadPool (pool); serverChannel = AsynchronousServerSocketChannel.open (group) .bind(new InetSocketAddress(configuration.getPort())); } catch (IOException e) { throw new RuntimeException(e); } } public void startup() { serverChannel.accept(null, new AcceptCompletionHandler(serverChannel, configuration.getReadBufferSize())); try { group.awaitTermination(Long.MAX_VALUE , TimeUnit.SECONDS ); } catch (InterruptedException e) { throw new RuntimeException(e); } } public void shutdown() { try { serverChannel.close(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { group.shutdown(); } catch (Exception e) { throw new RuntimeException(e); } finally { try { pool.shutdown(); } catch (Exception e) { throw new RuntimeException(e); } } } } } |

AcceptCompletionHandler.java

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * @author Bright Lee */ public final class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Void> { private final AsynchronousServerSocketChannel serverChannel; private final int readBufferSize; public AcceptCompletionHandler(AsynchronousServerSocketChannel serverChannel, int readBufferSize) { this.serverChannel = serverChannel; this.readBufferSize = readBufferSize; } @Override public void completed(AsynchronousSocketChannel clientChannel, Void attachment) { // 必须:立即再次发起 accept ,以便接受后续连接 if (serverChannel.isOpen()) { serverChannel.accept(null, new AcceptCompletionHandler(serverChannel, readBufferSize)); } // 为当前客户端连接启动异步读取 ReadCompletionHandler readCompletionHandler = new ReadCompletionHandler(clientChannel, readBufferSize); clientChannel.read(readCompletionHandler.getReadAttachment(), readCompletionHandler.getReadAttachment(), readCompletionHandler); } @Override public void failed(Throwable e, Void attachment) { e.printStackTrace(); } } |

ReadCompletionHandler.java

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * @author Bright Lee */ public final class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> { private final AsynchronousSocketChannel clientChannel; private final ByteBuffer readAttachment; private final WriteCompletionHandler writeCompletionHandler; public ReadCompletionHandler(AsynchronousSocketChannel clientChannel, int readBufferSize) { this.clientChannel = clientChannel; this.readAttachment = ByteBuffer.allocate (readBufferSize); this.writeCompletionHandler = new WriteCompletionHandler(this); } AsynchronousSocketChannel getClientChannel() { return clientChannel; } ByteBuffer getReadAttachment() { return readAttachment; } @Override public void completed(Integer result, ByteBuffer readAttachment) { // 翻转缓冲区,准备读取数据 readAttachment.flip(); byte\[\] data = new bytereadAttachment.remaining(); readAttachment.get(data); String message = new String(data).toUpperCase(); System.out .println("收到并处理: " + message); // 异步写回响应 readAttachment.clear(); clientChannel.write(ByteBuffer.wrap (message.getBytes()), null, writeCompletionHandler); } @Override public void failed(Throwable t, ByteBuffer buf) { t.printStackTrace(); try { clientChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } |

WriteCompletionHandler.java

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; /** * @author Bright Lee */ public final class WriteCompletionHandler implements CompletionHandler<Integer, Void> { private final AsynchronousSocketChannel clientChannel; private final ByteBuffer writeAttachment; private final ReadCompletionHandler readCompletionHandler; public WriteCompletionHandler(ReadCompletionHandler readCompletionHandler) { this.clientChannel = readCompletionHandler.getClientChannel(); this.writeAttachment = ByteBuffer.allocate (1024); this.readCompletionHandler = readCompletionHandler; } AsynchronousSocketChannel getClientChannel() { return clientChannel; } ByteBuffer getWriteAttachment() { return writeAttachment; } @Override public void completed(Integer result, Void attachment) { // 写完后,清空缓冲区,继续读取下一条消息 final ByteBuffer readAttachment = readCompletionHandler.getReadAttachment(); readAttachment.clear(); clientChannel.read(readAttachment, readAttachment, readCompletionHandler); } @Override public void failed(Throwable t, Void attachment) { t.printStackTrace(); try { clientChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } |

Nio2ServerTest.java

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| /** * @author Bright Lee */ public final class Nio2ServerTest { public static void main(String\[\] args) { Server server = new Server(); server.startup(); } } |

Nio2ClientTest.java

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /** * @author Bright Lee */ public final class Nio2ClientTest { public static void main(String\[\] args) throws IOException { Configuration configuration = new Configuration(); Socket socket = new Socket("localhost", configuration.getPort()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader console = new BufferedReader(new InputStreamReader(System.in )); System.out .println("已连接到服务端"); String line; while ((line = console.readLine()) != null) { out.println(line); System.out .println("服务端回复: " + in.readLine()); } } } |

相关推荐
白露与泡影3 小时前
Spring AI Alibaba -- 文生图、文生音及向量化
java·人工智能·spring
古城小栈3 小时前
Rust 学习路线,供初学者参考
开发语言·rust
学长毕设3 小时前
基于springboot的社会志愿者管理系统-附源码
java·spring boot·后端
喵了几个咪3 小时前
GoWind CMS 拆解:给 NL2SQL 上四把锁——智能问数的安全边界
开发语言·后端·安全·微服务·golang·gowind
多弗朗皮卡丘3 小时前
C++的类型转换
开发语言·c++
木头科技4 小时前
【AI 工程化第十六篇】Spring AI 多模态 RAG 实战:图片、扫描件、表格与图文证据链
java·人工智能·spring
FLJwu4 小时前
运动相机图像传感器选型实战|第二篇:参数看着一模一样,为什么骑行录像疯狂果冻、拖影翻车?
android·c语言·开发语言·数码相机·运动相机·oem 量产
驭渊的小故事4 小时前
从 JVM 底层看泛型:泛型擦除、Signature 属性与 Super Type Token 模式
java·开发语言·jvm
菜鸟小杰子4 小时前
手动修改 Spring Boot 嵌套 JAR 包:大包小包隔离打包实战
java·jar