使用 php 监听 WebSocket

Listen WebSocket with php

我想借助 Websocket 获得 Binance 上的即时加密货币价格。我可以用 javascript 来做到这一点,如下所示。但是,这对我没有用,因为 javascript 在客户端工作。我想在服务器上使用 php 到 运行 来执行此操作。我在研究中找到了一些例子,但它们不是我的解决方案。

下面是一个 javascript 示例,我想在 php 中学习如何操作。

var socket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");

socket.onmessage = function (event) {
    var data = JSON.parse(event.data);
    console.log(data);
}

我有两个 类 可以用来从 php

连接到 websocket 服务器

来源位于https://github.com/napengam/phpWebSocketServer/tree/master/phpClient

<?php

include __DIR__ . "/../phpClient/websocketCore.php";

class websocketPie extends websocketCore {

    public $uuid, $connected = false, $chunkSize = 6 * 1024;

    //private $socketMaster;

    function __construct($Address, $Port = '', $app = '/', $uu = '') {

        if (parent::__construct($Address, $Port, $app, $uu) == false) {
            return;
        }
       
        $respo = $this->readSocket();
        echo var_dump(json_decode($respo));
    }

}

$x = new websocketPie("wss://stream.binance.com","9443","/ws/btcusdt@ticker");

上面脚本的输出如下:

F:\xampp-htdocs\phpWebSocketServer\websocketExtern\websocketPie_1.php:18:
object(stdClass)[2]
  public 'e' => string '24hrTicker' (length=10)
  public 'E' => int 1626263895576
  public 's' => string 'BTCUSDT' (length=7)
  public 'p' => string '-623.48000000' (length=13)
  public 'P' => string '-1.885' (length=6)
  public 'w' => string '32342.75143871' (length=14)
  public 'x' => string '33074.69000000' (length=14)
  public 'c' => string '32451.21000000' (length=14)
  public 'Q' => string '0.00356600' (length=10)
  public 'b' => string '32451.21000000' (length=14)
  public 'B' => string '0.00534800' (length=10)
  public 'a' => string '32451.22000000' (length=14)
  public 'A' => string '0.40745100' (length=10)
  public 'o' => string '33074.69000000' (length=14)
  public 'h' => string '33078.98000000' (length=14)
  public 'l' => string '31550.00000000' (length=14)
  public 'v' => string '51376.85373100' (length=14)
  public 'q' => string '1661668809.92454695' (length=19)
  public 'O' => int 1626177495575
  public 'C' => int 1626263895575
  public 'F' => int 954365122
  public 'L' => int 955537825
  public 'n' => int 1172704