onWorkerStart里面是stream流数据,前端连接不上的问题,求解答

jiangwz

问题描述,谢谢解答

onWorkerStart里面是stream流数据,导致前端连接失败,因为在不停的推送数据,默认没有执行完成,求1个思路,感谢。

后端代码

<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;

require 'vendor/autoload.php';

$worker = new Worker("websocket://127.0.0.1:2000");

$worker->onWorkerStart = function ($worker) {
    // 创建一个 Guzzle 客户端实例
    $client = new Client();

    // 设置请求头
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer 123456789...'
    ];

    // 发起请求并传递请求头
    $promise = $client->getAsync('这里是一个流链接地址,会不停的推送如下图所示的数据', [
        'headers' => $headers,
        'stream' => true
    ]);

    // 等待Promise解析为响应
    $response = $promise->wait();

    // 检查响应是否成功
    if ($response->getStatusCode() == 200) {
        // 获取响应体流
        $body = $response->getBody();

        // 逐行读取数据
        while (!$body->eof()) {
            $line = Psr7\Utils::readLine($body);
            if ($line) {
                var_dump($line);

                // 在这里我想实现,把line数据推送给前端连接对象,$line数据格式如下图所示
                // 但是前端连接不上,上面代码[ while (!$body->eof()) { ]逐行读取影响了,因为在不停的推送数据,没有执行完成
                // 上面的while注释掉,前端可以连接成功
            }
        }

        // 关闭流
        $body->close();
    } else {
        echo "请求失败: " . $response->getStatusCode() . "\n";
    }
};

// 当客户端建立连接时,不匹配则主动断开
$worker->onConnect = function ($connection) {
    $connection->onWebSocketConnect = function ($connection, $http_header) {
        $token = $_GET["token"];
        $symbol = $_GET["symbol"];

        if ($token != '673eb112dcd3ca2a2d7024a84d8cd6ef') {
            $connection->close();
        } else {
            $connection->symbol = $symbol;
        }
    };
};

// 当有客户端发来消息时,执行的回调函数
$worker->onMessage = function (TcpConnection $connection, $data) {
    if ($data == "pong") {
        $connection->send('heartbeat');
    }
};

// 向所有验证的用户推送对应的数据
function broadcast($msg, $symbol)
{
    global $worker;
    foreach ($worker->connections as $connection) {
        $connection->send($msg);
    }
}

// 运行worker
Worker::runAll();

前端代码

<script type="text/javascript">
    ws = new WebSocket("ws://127.0.0.1/?token=673eb112dcd3ca2a2d7024a84d8cd6ef&symbol=EUR_USD");

    ws.onopen = function() {
        console.log("连接成功");
        var heartbeat = setInterval(function(){
            ws.send('pong');
        },10000);
    }

    ws.onmessage = function(e) {
        console.log(e.data);
    }
</script>

数据截图

414 1 0
1个回答

walkor 打赏

workerman/http-client 替换guzzle

×
🔝