要處理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
現(xiàn)在,您可以使用STOMP客戶端連接到WebSocket服務(wù)器并發(fā)送/接收消息。這是一個簡單的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();
運(yùn)行此客戶端以發(fā)送消息到STOMP服務(wù)器,服務(wù)器將把消息廣播給所有訂閱了該主題的其他客戶端。