Files
shop-platform/docs/websocket/README.md

356 lines
7.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
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.
# WebSocket Server 说明文档
## 1. 概述
WebSocket Server 是基于 Ratchet 库实现的纯 PHP WebSocket 服务器,主要用于为智能客服系统提供实时通信支持,特别是为不支持 EventSource 的微信小程序提供流式请求处理能力。
## 2. 安装与依赖
### 2.1 依赖库
- **Ratchet**: 纯 PHP WebSocket 实现库
```bash
composer require cboden/ratchet
```
### 2.2 环境要求
- PHP 7.4+
- Composer
- ThinkPHP 6.x
## 3. 服务器文件结构
### 3.1 核心文件
- **启动脚本**: `src/ws_server.php` - WebSocket 服务器主启动文件
- **智能客服控制器**: `src/addon/aikefu/api/controller/WebSocket.php` - aikefu 插件的 WebSocket 控制器实现
### 3.2 目录结构
```
├── backend/
│ ├── docs/
│ │ └── websocket/
│ │ └── README.md # 本文档
│ └── src/
│ ├── ws_server.php # WebSocket 服务器启动脚本
│ └── addon/
│ └── aikefu/
│ └── api/
│ └── controller/
│ └── WebSocket.php # aikefu 插件 WebSocket 控制器
```
## 4. 服务器启动与配置
### 4.1 启动命令
在 `src` 目录下执行:
```bash
php ws_server.php
```
### 4.2 默认配置
- **监听地址**: `0.0.0.0` (所有网络接口)
- **端口**: `8080`
- **WebSocket 地址**: `ws://localhost:8080`
### 4.3 自定义配置
可以在 `ws_server.php` 中修改以下配置:
```php
// 配置WebSocket服务器
$httpHost = 'localhost'; // 客户端连接时使用的主机名
$port = 8080; // WebSocket服务器端口
$address = '0.0.0.0'; // 监听所有网络接口
```
## 5. WebSocket 路径
### 5.1 默认测试路径
- **路径**: `/ws`
- **功能**: 用于测试 WebSocket 连接
- **示例**: `ws://localhost:8080/ws`
### 5.2 智能客服路径
- **路径**: `/ws/aikefu`
- **功能**: 智能客服聊天功能接口
- **示例**: `ws://localhost:8080/ws/aikefu`
## 6. 消息格式
### 6.1 客户端发送消息格式
```json
{
"message": "用户输入的消息",
"token": "用户认证令牌",
"session_id": "会话ID",
"action": "chat" // 动作类型
}
```
### 6.2 服务器响应消息格式
#### 聊天响应
```json
{
"type": "chat",
"message": "客服回复的消息内容",
"session_id": "会话ID",
"complete": false // 是否完成响应
}
```
#### 错误响应
```json
{
"type": "error",
"message": "错误信息描述",
"code": "错误代码"
}
```
#### 系统消息
```json
{
"type": "system",
"message": "系统消息内容"
}
```
## 7. 客户端使用示例
### 7.1 JavaScript 示例
```javascript
// 创建WebSocket连接
const ws = new WebSocket('ws://localhost:8080/ws/aikefu');
// 连接打开时
ws.onopen = function(event) {
console.log('WebSocket连接已打开');
// 发送聊天消息
ws.send(JSON.stringify({
message: '你好',
token: 'user_token_here',
session_id: 'session_123',
action: 'chat'
}));
};
// 接收消息
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('收到消息:', data);
if (data.type === 'chat') {
// 处理聊天消息
console.log('客服回复:', data.message);
if (data.complete) {
console.log('对话完成');
}
} else if (data.type === 'error') {
// 处理错误
console.error('错误:', data.message);
}
};
// 连接关闭时
ws.onclose = function(event) {
console.log('WebSocket连接已关闭');
};
// 连接错误时
ws.onerror = function(error) {
console.error('WebSocket错误:', error);
};
```
### 7.2 微信小程序示例
```javascript
// 创建WebSocket连接
const ws = wx.connectSocket({
url: 'ws://localhost:8080/ws/aikefu',
header: {
'content-type': 'application/json'
}
});
// 连接打开时
wx.onSocketOpen(function(res) {
console.log('WebSocket连接已打开', res);
// 发送聊天消息
wx.sendSocketMessage({
data: JSON.stringify({
message: '你好',
token: 'user_token_here',
session_id: 'session_123',
action: 'chat'
})
});
});
// 接收消息
wx.onSocketMessage(function(res) {
const data = JSON.parse(res.data);
console.log('收到消息:', data);
if (data.type === 'chat') {
// 处理聊天消息
console.log('客服回复:', data.message);
if (data.complete) {
console.log('对话完成');
}
} else if (data.type === 'error') {
// 处理错误
console.error('错误:', data.message);
}
});
// 连接关闭时
wx.onSocketClose(function(res) {
console.log('WebSocket连接已关闭', res);
});
// 连接错误时
wx.onSocketError(function(res) {
console.error('WebSocket错误:', res);
});
```
## 8. 功能特性
### 8.1 实时通信
- 支持双向实时通信
- 消息即时推送
- 支持流式响应
### 8.2 智能客服集成
- 与现有智能客服系统无缝集成
- 支持上下文会话管理
- 支持多用户并发访问
### 8.3 插件化设计
- 支持为不同插件注册独立的 WebSocket 控制器
- 路径格式:`/ws/{addon_name}`
- 便于扩展其他插件的 WebSocket 支持
## 9. 故障排除
### 9.1 常见问题
#### 问题:服务器无法启动
**可能原因**
- 端口被占用
- 依赖库未安装
- PHP 版本不兼容
**解决方案**
- 检查端口占用情况:`netstat -an | findstr 8080`
- 重新安装依赖:`composer install`
- 确保 PHP 版本 >= 7.4
#### 问题:客户端无法连接
**可能原因**
- 服务器未启动
- 网络防火墙限制
- WebSocket 地址错误
**解决方案**
- 确认服务器已启动
- 检查防火墙设置,确保端口 8080 开放
- 验证 WebSocket 地址格式
#### 问题:消息发送失败
**可能原因**
- 消息格式错误
- 认证失败
- 服务器内部错误
**解决方案**
- 检查消息格式是否符合要求
- 验证用户认证信息
- 查看服务器日志获取详细错误信息
### 9.2 日志查看
服务器启动时会输出详细日志,包括:
- 已注册的 WebSocket 控制器
- 连接信息
- 错误信息
## 10. 扩展开发
### 10.1 为其他插件添加 WebSocket 支持
1. 在插件目录下创建 WebSocket 控制器:
```
addon/{addon_name}/api/controller/WebSocket.php
```
2. 实现 MessageComponentInterface 接口:
```php
<?php
namespace addon\{addon_name}\api\controller;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class WebSocket implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// 处理连接打开
}
public function onMessage(ConnectionInterface $conn, $msg) {
// 处理收到的消息
}
public function onClose(ConnectionInterface $conn) {
// 处理连接关闭
}
public function onError(ConnectionInterface $conn, \Exception $e) {
// 处理错误
}
}
```
3. 重启 WebSocket 服务器,新插件的 WebSocket 控制器将自动注册到 `/ws/{addon_name}` 路径
## 11. 版本历史
| 版本 | 日期 | 说明 |
|------|------|------|
| v1.0 | 2025-12-19 | 初始版本,支持智能客服系统的 WebSocket 通信 |
## 12. 联系方式
如有问题或建议,请联系技术支持团队。