110 lines
2.0 KiB
Markdown
110 lines
2.0 KiB
Markdown
# WebSocket 聊天服务器
|
||
|
||
基于 Node.js、Express 和 WebSocket 实现的实时聊天服务器。
|
||
|
||
## 功能特性
|
||
|
||
- 支持群聊和私聊
|
||
- 在线用户列表
|
||
- 消息历史记录
|
||
- 心跳检测
|
||
- 自动断开超时连接
|
||
- CORS 跨域支持
|
||
- 健康检查接口
|
||
|
||
## 安装依赖
|
||
|
||
1. 进入项目目录:
|
||
```bash
|
||
cd chat-server
|
||
```
|
||
|
||
2. 安装依赖:
|
||
```bash
|
||
npm install
|
||
```
|
||
|
||
## 配置
|
||
|
||
1. 复制环境变量示例文件:
|
||
```bash
|
||
cp .env.example .env
|
||
```
|
||
|
||
2. 根据需要修改 `.env` 文件中的配置:
|
||
- `CHAT_SERVER_PORT`:服务器监听端口(默认3100)
|
||
- `ALLOWED_ORIGINS`:允许连接的前端域名,多个域名用逗号分隔
|
||
- `DEBUG`:是否启用调试模式
|
||
|
||
## 启动服务器
|
||
|
||
### 开发模式
|
||
|
||
使用 nodemon 启动服务器,支持代码修改自动重启:
|
||
```bash
|
||
npm run dev
|
||
```
|
||
|
||
### 生产模式
|
||
|
||
直接启动服务器:
|
||
```bash
|
||
npm start
|
||
```
|
||
|
||
## 健康检查
|
||
|
||
服务器启动后,可以通过访问 `http://localhost:3100/health` 检查服务器状态。
|
||
|
||
## WebSocket 客户端集成
|
||
|
||
1. 连接服务器:
|
||
```javascript
|
||
const ws = new WebSocket('ws://localhost:3100')
|
||
```
|
||
|
||
2. 消息格式:
|
||
```javascript
|
||
// 发送聊天消息(群发)
|
||
ws.send(JSON.stringify({
|
||
type: 'chat',
|
||
content: '消息内容'
|
||
}))
|
||
|
||
// 发送私聊消息
|
||
ws.send(JSON.stringify({
|
||
type: 'chat',
|
||
to: { id: '目标用户ID', name: '目标用户名称' },
|
||
content: '私聊消息内容'
|
||
}))
|
||
|
||
// 更新用户信息
|
||
ws.send(JSON.stringify({
|
||
type: 'user',
|
||
action: 'update',
|
||
name: '新的用户名'
|
||
}))
|
||
|
||
// 发送心跳
|
||
ws.send(JSON.stringify({
|
||
type: 'ping'
|
||
}))
|
||
```
|
||
|
||
3. 接收消息:
|
||
```javascript
|
||
ws.onmessage = (event) => {
|
||
const message = JSON.parse(event.data)
|
||
switch (message.type) {
|
||
case 'chat':
|
||
// 处理聊天消息
|
||
break
|
||
case 'system':
|
||
// 处理系统消息(用户加入/离开、用户列表更新等)
|
||
break
|
||
case 'pong':
|
||
// 处理心跳响应
|
||
break
|
||
}
|
||
}
|
||
``` |