侦探大挑战
128.12M · 2026-04-22
smart-socket 是 smartboot 组织开源的 Java AIO(Asynchronous I/O,异步 IO)通信框架:项目自述为“100% 遵循 JDK AIO 接口规范,但重新实现一套代码”,以获得更高通信性能、更少资源开销与更稳定运行;使用上主打极简(核心只需实现 Protocol + MessageProcessor 两个接口),并提供 SSL/TLS、心跳、断链重连、黑名单、监控等插件能力(见项目 README 插件清单)。
Protocol、MessageProcessor 两个接口(README)| 项目 | 定位 | 上手成本 | 部署方式 | 生态/集成 | 许可 | 典型坑 |
|---|---|---|---|---|---|---|
| smart-socket | Java AIO 通信框架(自定义协议/长连接) | 低(2 个接口起步) | Maven | 插件:TLS/心跳/重连/监控/黑名单等(README) | Apache-2.0 | 需要自己设计协议与拆包;版本选择需核对文档与 tag;长连接治理要配合心跳/超时/限流 |
| Netty | Java NIO 通信框架/网络基础设施 | 中-高 | Maven | 生态极强(大量框架/组件依赖) | Apache-2.0 | 概念多(Pipeline/ByteBuf);内存与背压处理容易踩坑 |
| Apache MINA | Java 网络应用框架(NIO 为主) | 中 | Maven | 生态中等 | Apache-2.0(待核实:以其官方仓库 LICENSE 为准) | 维护活跃度与版本节奏需你核对(看最近 tag/commit/issue) |
前置:JDK 8+(官方文档页写法),Maven。
v1.8.2<dependency>
<groupId>io.github.smartboot.socket</groupId>
<artifactId>aio-core</artifactId>
<version>1.8.2</version>
</dependency>
StringProtocol(长度字段拆包):
import java.nio.ByteBuffer;
import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;
public class StringProtocol implements Protocol<String> {
@Override
public String decode(ByteBuffer readBuffer, AioSession session) {
if (readBuffer.remaining() < Integer.BYTES) return null;
readBuffer.mark();
int length = readBuffer.getInt();
if (length > readBuffer.remaining()) {
readBuffer.reset();
return null;
}
byte[] b = new byte[length];
readBuffer.get(b);
return new String(b);
}
}
Server:
import java.io.IOException;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.transport.AioQuickServer;
import org.smartboot.socket.transport.WriteBuffer;
public class StringServer {
public static void main(String[] args) throws IOException {
MessageProcessor<String> processor = (session, msg) -> {
WriteBuffer out = session.writeBuffer();
byte[] bytes = msg.getBytes();
try {
out.writeInt(bytes.length);
out.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
};
new AioQuickServer(8888, new StringProtocol(), processor).start();
System.out.println("listen :8888");
}
}
Client:
import java.io.IOException;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.transport.AioQuickClient;
import org.smartboot.socket.transport.AioSession;
import org.smartboot.socket.transport.WriteBuffer;
public class StringClient {
public static void main(String[] args) throws IOException {
MessageProcessor<String> processor = (session, msg) -> System.out.println("resp: " + msg);
AioSession session = new AioQuickClient("127.0.0.1", 8888, new StringProtocol(), processor).start();
WriteBuffer out = session.writeBuffer();
byte[] data = "hello smart-socket".getBytes();
out.writeInt(data.length);
out.write(data);
out.flush();
}
}