要处理PHP STOMP消息,您需要遵循以下步骤:
composer require cboden/ratchet
// server.php
require 'vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\StompHandler;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new StompHandler()
)
),
8080
);
$server->run();
// MyApp/StompHandler.php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Stomp\Client as StompClient;
class StompHandler implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
}
php server.php
现在,您可以使用STOMP客户端连接到WebSocket服务器并发送/接收消息。这是一个简单的STOMP客户端示例:
// stomp_client.php
require 'vendor/autoload.php';
use Stomp\Client;
$client = new Client('ws://localhost:8080');
$client->connect();
$client->subscribe('/topic/my_topic', function ($message) {
echo "Received message: {$message->body}\n";
});
$client->send('/topic/my_topic', '', 'Hello, World!');
sleep(10);
$client->disconnect();
运行此客户端以发送消息到STOMP服务器,服务器将把消息广播给所有订阅了该主题的其他客户端。