websocket php实现聊天
使用 PHP 和 WebSocket 实现聊天功能
准备工作
确保服务器支持 WebSocket 协议,安装 PHP 的 WebSocket 库,如 Ratchet。通过 Composer 安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务器
创建一个 PHP 文件(如 server.php),编写 WebSocket 服务器逻辑:
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection: {$conn->resourceId}\n";
}
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);
echo "Connection closed: {$conn->resourceId}\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
$server->run();
启动服务器
在终端运行以下命令启动 WebSocket 服务器:
php server.php
创建客户端页面
编写 HTML 和 JavaScript 代码,连接到 WebSocket 服务器:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<div id="messages"></div>
<input type="text" id="message" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = function(e) {
document.getElementById('messages').innerHTML += `<p>${e.data}</p>`;
};
function sendMessage() {
const message = document.getElementById('message').value;
socket.send(message);
document.getElementById('message').value = '';
}
</script>
</body>
</html>
测试聊天功能
在浏览器中打开客户端页面,输入消息并发送。消息将通过 WebSocket 服务器广播给所有连接的客户端。
部署到生产环境
在生产环境中,建议使用 Nginx 或 Apache 作为反向代理,将 WebSocket 流量转发到 PHP 服务器。配置 Nginx 示例:
location /chat {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
扩展功能
可以添加用户认证、消息存储、房间分组等功能。例如,修改 Chat 类以支持用户昵称:
public function onMessage(ConnectionInterface $from, $msg) {
$data = json_decode($msg, true);
foreach ($this->clients as $client) {
$client->send(json_encode([
'user' => $data['user'],
'message' => $data['message']
]));
}
}
注意事项
- WebSocket 服务器需要长时间运行,建议使用
supervisord或systemd管理进程。 - 确保服务器防火墙允许 WebSocket 端口(如 8080)的流量。
- 对于高并发场景,考虑使用更高效的 WebSocket 实现,如
Swoole。







