php实现群聊
PHP实现群聊功能
基础架构设计
使用WebSocket协议实现实时通信,PHP可通过Ratchet库处理WebSocket连接。建立服务器端脚本监听特定端口,客户端通过JavaScript WebSocket API连接。
服务器端实现
安装Ratchet库:composer require cboden/ratchet
创建WebSocket服务器脚本(chat_server.php):
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require dirname(__DIR__) . '/vendor/autoload.php';
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($client !== $from) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
客户端实现
HTML页面加入WebSocket连接代码:
<script>
const conn = new WebSocket('ws://localhost:8080');
conn.onmessage = e => {
document.getElementById('messages').innerHTML += `<div>${e.data}</div>`;
};
function sendMessage() {
const msg = document.getElementById('message').value;
conn.send(msg);
}
</script>
<div id="messages"></div>
<input id="message" type="text">
<button onclick="sendMessage()">Send</button>
用户身份管理
扩展服务器端代码存储用户信息:
public function onOpen(ConnectionInterface $conn) {
$query = $conn->httpRequest->getUri()->getQuery();
parse_str($query, $params);
$conn->username = $params['username'] ?? 'Anonymous';
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
$client->send("[{$from->username}] {$msg}");
}
}
消息持久化
集成数据库存储聊天记录(MySQL示例):
public function onMessage(ConnectionInterface $from, $msg) {
$pdo = new PDO('mysql:host=localhost;dbname=chat', 'user', 'pass');
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->execute([$from->username, $msg]);
foreach ($this->clients as $client) {
$client->send("[{$from->username}] {$msg}");
}
}
部署运行
启动WebSocket服务器:php chat_server.php
保持服务器运行可使用Supervisor等进程管理工具。
扩展功能建议
- 添加私聊功能,通过消息前缀识别目标用户
- 实现用户列表广播,在onOpen/onClose时通知所有客户端
- 增加消息过滤机制防止XSS攻击
- 支持图片/文件传输(需Base64编码)
- 添加历史消息查询接口
注意:生产环境应考虑使用Nginx反向代理WebSocket连接,并配置SSL加密(wss://)。对于高并发场景,建议考虑专业即时通讯解决方案或使用Swoole扩展替代Ratchet。







