簡體   English   中英

PHP中是否有踩過websocket?

[英]Is there stomp over websocket in PHP?

我使用 Node.js 在 WebSocket 上運行 STOMP,因為它支持自定義標頭。 當 HTTP 握手時,服務器需要一個 cookie 來檢查身份驗證,而不是地址中的令牌。

作為PHPer,想在PHP中使用這個,但是google了半天也沒找到辦法。 誰能幫忙?

STOMP不限於Node.js,或者Java等,還有

關於您的具體情況,在不了解更多細節的情況下很難直接給出答案,但這里有一個來自 stomp-php 庫示例帽子的示例,其中設置了自定義 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"; }

如果要使用協議進行連接,則需要 websocket stream 包裝器

你可以使用 php-stomp-frame

https://github.com/jeenn/php-stomp-frame

作曲家需要 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM