Files
ws.tootaio.com/README.md
2025-10-07 11:59:55 +08:00

175 lines
3.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
好的 👍 我来帮你写一份专业的 **README.md**,既能让开发者快速上手,又能作为项目的正式说明文档。这里我会结合你的代码仓库结构和实现特点来写。
---
# README.md
# 🚀 WebSocket + Redis Pub/Sub Service
本项目是一个基于 **WebSocket****Redis** 的实时消息推送服务,支持多客户端订阅、消息分发与发布。
通过 `docker-compose` 可一键启动服务,方便部署与扩展。
---
## 📂 项目结构
```
.
├── client/
│ └── test-client.js # WebSocket 客户端示例(测试用)
├── server/
│ ├── Dockerfile # 服务端 Docker 构建配置
│ ├── index.js # WebSocket + Redis 服务端逻辑
│ └── package.json # Node.js 依赖配置
└── docker-compose.yml # 服务编排配置
```
---
## ⚙️ 功能特性
* 🔑 **认证机制**:客户端需通过 `auth` 消息声明 `app` 名称。
* 📡 **订阅/取消订阅**:客户端可动态订阅频道,实时接收消息。
* 📤 **消息发布**:通过 Redis Pub/Sub 将消息广播至所有订阅者。
* 🛠 **易于扩展**:支持分布式部署,多个 WebSocket 节点可共享 Redis。
---
## 🚀 快速开始
### 1⃣ 启动服务
确保已安装 **Docker****Docker Compose**
```bash
docker compose up -d
```
服务启动后默认监听:
```
ws://localhost:8080
```
### 2⃣ 运行测试客户端
```bash
node client/test-client.js
```
预期输出:
```
✅ 已连接 WebSocket
📩 收到消息: {"type":"auth_ok","app":"demo"}
📩 收到消息: {"type":"subscribed","channel":"chat"}
📩 收到消息: {"app":"demo","channel":"chat","event":"message","data":{"text":"Hello Redis WS 🚀"}}
```
---
## 📡 协议说明
所有消息均为 **JSON 格式**,字段如下:
### 🔑 认证
```json
{ "type": "auth", "app": "demo" }
```
服务端响应:
```json
{ "type": "auth_ok", "app": "demo" }
```
### 📌 订阅频道
```json
{ "type": "subscribe", "channel": "chat" }
```
服务端响应:
```json
{ "type": "subscribed", "channel": "chat" }
```
### 📤 发布消息
```json
{
"type": "publish",
"app": "demo",
"channel": "chat",
"event": "message",
"data": { "text": "Hello Redis WS 🚀" }
}
```
被订阅该频道的客户端将收到:
```json
{
"app": "demo",
"channel": "chat",
"event": "message",
"data": { "text": "Hello Redis WS 🚀" }
}
```
---
## 🐳 环境变量
通过 `docker-compose.yml` 设置:
| 变量名 | 默认值 | 说明 |
| ---------------- | ------------ | -------------- |
| `REDIS_HOST` | `main_redis` | Redis 主机地址 |
| `REDIS_PORT` | `6379` | Redis 端口 |
| `REDIS_PASSWORD` | 空字符串 | Redis 密码 |
---
## 📦 构建与部署
### 本地构建镜像
```bash
docker build -t websocket-server ./server
```
### 运行容器
```bash
docker run -d -p 8080:8080 --name ws-server websocket-server
```
---
## 📖 技术栈
* **WebSocket** (`ws`): 提供实时通信能力
* **Redis** (`ioredis`): 实现分布式消息队列与广播
* **Docker** + **Docker Compose**: 快速部署与服务编排
---
## 📝 注意事项
* 本项目的 `Repomix` 合并文件仅供分析和审查,请勿直接修改。
* 如果需要调整功能,请修改原始仓库中的对应文件。
* 确保 Redis 服务正常运行,否则消息发布/订阅功能不可用。
---
## 📜 License
[ISC](./server/package.json)
---
要不要我帮你在 README 里再加一张 **架构图WebSocket + Redis Pub/Sub 流程)**?这样别人一眼就能看懂整个系统的消息流向 🔄。