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()); } } } |

相关推荐
七夜zippoe25 分钟前
Nexent 知识库:调优靠 Chunk 与重排
开发语言·python·ai智能体·nexent·知识库与rag
.痞老板.1 小时前
java ee--文件操作和IO
java·java-ee
简 洁 冬冬1 小时前
分页「向上取整」公式 `(total + size - 1) / size` 的完整推导
java·分页
kyle~2 小时前
C# --- 反射
开发语言·c#
soso19682 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
装不满的克莱因瓶3 小时前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba
Risehuxyc3 小时前
来自PHP项目devnexen的回信
开发语言·php
FRing033 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
SimonKing4 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
我是大猴子4 小时前
分析sss
开发语言