php 实现websocket
PHP 实现 WebSocket
要在 PHP 中实现 WebSocket,可以使用 Ratchet 库,它是一个流行的 PHP WebSocket 库,基于 ReactPHP 构建。以下是实现 WebSocket 服务端和客户端通信的详细方法。
安装 Ratchet
使用 Composer 安装 Ratchet:
composer require cboden/ratchet
创建 WebSocket 服务器
创建一个 PHP 文件(如 server.php),编写 WebSocket 服务器逻辑:
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require __DIR__ . '/vendor/autoload.php';
class MyWebSocket 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 MyWebSocket())),
8080
);
$server->run();
启动 WebSocket 服务器
在终端运行以下命令启动服务器:
php server.php
服务器将在 8080 端口监听 WebSocket 连接。
创建 WebSocket 客户端
使用 JavaScript 创建一个简单的 WebSocket 客户端:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<input type="text" id="message" placeholder="Enter message">
<button onclick="sendMessage()">Send</button>
<div id="output"></div>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = function(e) {
console.log('Connected to WebSocket server');
};
socket.onmessage = function(e) {
document.getElementById('output').innerHTML += `<p>${e.data}</p>`;
};
socket.onclose = function(e) {
console.log('Disconnected from WebSocket server');
};
function sendMessage() {
const message = document.getElementById('message').value;
socket.send(message);
}
</script>
</body>
</html>
测试 WebSocket 通信
- 确保服务器正在运行(
php server.php)。 - 在浏览器中打开客户端 HTML 文件。
- 输入消息并点击发送按钮,消息将通过 WebSocket 广播到所有连接的客户端。
注意事项
- 端口冲突:确保
8080端口未被占用,或修改为其他可用端口。 - 生产环境:在生产环境中,建议使用 Nginx 或 Apache 反向代理 WebSocket 连接。
- 扩展性:对于高并发场景,可能需要结合 Redis 或其他消息队列实现多服务器通信。
通过以上步骤,可以实现基本的 WebSocket 通信功能。







