I use Node.js to run STOMP over WebSocket because it supports custom headers. When HTTP handshake, the server needs a cookie to check auth, not the token in the address.
As PHPer, I want to use this in PHP, but search google for a long time and found no way. can anyone help?
STOMP is not limited to Node.js, or Java, etc. There are
Regarding your specific scenario, it's hard to come up with a straight-up answer without knowing more details but here is an example from the stomp-php library samples hat sets a custom header:
use Stomp\Client; use Stomp\SimpleStomp; use Stomp\Transport\Map; // make a connection $client = new Client('tcp://localhost:61613'); $stomp = new SimpleStomp($client); // send a message to the queue $body = array('city' => 'Belgrade', 'name' => 'Dejan'); $header = array(); $header['transformation'] = 'jms-map-json'; $mapMessage = new Map($body, $header); $client->send('/queue/test', $mapMessage); echo 'Sending array: '; print_r($body); $stomp->subscribe('/queue/test', 'transform-test', 'client', null, ['transformation' => 'jms-map-json']); /** @var Map $msg */ $msg = $stomp->read(); // extract if ($msg:= null) { echo 'Received array; '; print_r($msg->map); // mark the message as received in the queue $stomp->ack($msg); } else { echo "Failed to receive a message\n"; }
you need a websocket stream wrapper if you want to connect using a protocol
You can use php-stomp-frame
https://github.com/jeeinn/php-stomp-frame
composer require jeeinn/php-stomp-frame
// over wss
require __DIR__ . '/vendor/autoload.php';
$url = 'wss://echo.websocket.org:443';
$userName = 'test';
$password = 'passcode';
$queue = 'service_queue_v1.2';
$stompFrame = new \Stomp\Frame();
# connect frame
$connectFrame = $stompFrame->setLogin($userName, $password)->setHeartBeat(0, 10000)->getConnect();
# subscribe frame
$subscribeFrame = $stompFrame->getSubscribe($queue);
#use websocket
$client = new \WebSocket\Client($url);
$client->text($connectFrame);
//var_dump($client->isConnected());
$client->text($subscribeFrame);
# loop listening
while (true) {
try {
$message = $client->receive();
$parsed = $stompFrame->parser($message);
//print_r($parsed);
# Error, Break while loop to stop listening, Possibly log errors
if ($parsed['command'] == 'ERROR') {
echo $parsed['body'];
$client->close();
break;
}
// Deal your data
$data = json_decode($parsed['body'], true);
print_r($data);
// Act[enter image description here][4] on received message
// Later, Break while loop to stop listening
} catch (Exception $e) {
// Possibly log errors
echo $e->getMessage();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.