# RAT NetCMD
一个简单高效的网络命令传输底层库,专注于提供可靠的数据传输通道,不关心具体的业务逻辑和命令执行。
## 特性
- 🚀 高性能:内部统一使用MessagePack进行数据传输
- 🔌 多格式支持:支持JSON和纯文本用户接口
- 🌐 网络通信:支持TCP端口连接(未来版本支持Linux fd)
- ⚡ 异步设计:基于tokio异步运行时
- 🛠️ 模块化:通过特性门控制编译,按需启用功能
## 快速开始
### 添加依赖
```toml
[dependencies]
rat-net-cmd = { version = "0.1.1", features = ["full"] }
```
或者按需选择特性:
```toml
# 仅需要服务器端功能
rat_net_cmd = { version = "0.1.1", features = ["server", "json", "msgpack"] }
# 仅需要客户端功能
rat_net_cmd = { version = "0.1.1", features = ["client", "text", "msgpack"] }
```
### 基本用法
#### 服务器端
```rust
use rat_net_cmd::{Config, ConnectionMode, DataFormat, Server, Response};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 创建配置
let config = Config::new(
ConnectionMode::Port {
host: "127.0.0.1".to_string(),
port: 8080
},
DataFormat::Text // 或 DataFormat::Json
);
// 启动服务器
let mut server = Server::new(config)?;
server.listen().await?;
// 接受连接
let mut connection = server.accept().await?;
// 接收命令
let command = connection.receive_command().await?;
println!("收到命令: {}", command.data);
// 发送响应
let response = Response::new(format!("处理完成: {}", command.data));
connection.send_response(&response).await?;
Ok(())
}
```
#### 客户端
```rust
use rat_net_cmd::{Config, ConnectionMode, DataFormat, Client, Command};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 创建配置
let config = Config::new(
ConnectionMode::Port {
host: "127.0.0.1".to_string(),
port: 8080
},
DataFormat::Text // 或 DataFormat::Json
);
// 创建客户端
let client = Client::new(config)?;
// 发送命令
let command = Command::new("hello".to_string());
let response = client.send_command(&command).await?;
println!("收到响应: {}", response.data);
Ok(())
}
```
### JSON模式示例
```rust
// JSON格式命令
let json_command = r#"{"action": "ping", "data": "hello"}"#;
let command = Command::new(json_command.to_string());
let response = client.send_command(&command).await?;
println!("JSON响应: {}", response.data);
```
## 特性门
| `server` | 服务器端功能 | ✅ |
| `client` | 客户端功能 | ✅ |
| `json` | JSON格式支持 | ❌ |
| `text` | 纯文本格式支持 | ✅ |
| `auth` | 鉴权功能支持 | ✅ |
| `full` | 包含所有功能 | ❌ |
**注意:** MessagePack是库的内部传输格式,始终启用,不是可选特性。
## 数据流程
```
用户输入 → JSON/TXT格式 → MessagePack编码 → 网络传输 → MessagePack解码 → 原始数据返回
```
无论用户选择JSON还是Text模式,库内部都会统一转换为MessagePack进行高效传输。
## 示例
项目包含完整的示例代码:
- **基础示例**:`cargo run --example basic --features full`
- **JSON示例**:`cargo run --example json --features full`
## 项目结构
```
src/
├── lib.rs # 库入口,特性门控制
├── error.rs # 错误处理模块
├── config.rs # 配置系统
├── codec.rs # MessagePack编解码
├── transport.rs # 网络传输层
├── server.rs # 服务器端实现
├── client.rs # 客户端实现
└── types.rs # 共享类型定义
```
## 版本历史
📖 **[更新日志](docs/CHANGELOG.md)**
## 许可证
LGPL-3.0
## 贡献
欢迎提交Issue和Pull Request!
## 设计理念
RAT NetCMD专注于成为一个简单可靠的底层网络传输库,不关心具体的业务逻辑。它为上层应用提供标准化的数据传输通道,让开发者可以专注于业务逻辑的实现。