要在PHP中实现WebSocket,可以使用开源库,如Ratchet
或Swoole
。这些库提供了WebSocket服务器的实现WebSocket连接、消息发送和接收。
本章介绍使用 Ratchet 库来实现Websocket
1.安装 Ratchet
安装开始前,请确保在你的项目根目录下的composer.json
文件包含以下内容,若无composer.json
文件或不存在以下内容,请手动创建文件或添加内容
{
"require": {
"cboden/ratchet": "^0.4" // 此处表示约束版本为 0.4
}
}
然后运行以下命令来安装Ratchet
composer install
2.编写服务脚本文件
<?php
require 'vendor/autoload.php'; // 引入Composer自动加载文件
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class MyWebSocketServer 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) {
// 当收到消息时触发
echo "Received message: {$msg}\n";
// 向所有连接的客户端发送消息
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
// 当连接关闭时触发
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
// 当发生错误时触发
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new MyWebSocketServer()
)
),
8080 // 设置WebSocket服务器监听的端口号
);
$server->run();
php websocket_server.php
执行以上命令,开始创建一个WebSocket服务器,监听8080端口。
3.前端连接websocket服务
var connection = new WebSocket('ws://localhost:8080');
connection.onopen = function () {
console.log('Connected to the server!');
connection.send('你好呀!');
};
connection.onmessage = function (event) {
console.log('服务器说', event.data);
};
connection.onclose = function () {
console.log('断开啦,再见');
};
下一章将会讲PHP Swoole 如何使用Websocket