websocket发送数据出错

katray608

问题描述

小白求教,让大佬见笑了
连接正常,客户端发送数据的时候出错了

程序代码

#!/usr/bin/env php
<?php

use Workerman\Worker;

require_once __DIR__ . '/vendor/autoload.php';

// Create a Websocket server
$ws_worker = new Worker('websocket://0.0.0.0:3921');

// Emitted when new connection come
$ws_worker->onConnect = function ($connection) {
    echo "New connection\n";
};

// Emitted when data received
$ws_worker->onMessage = function ($connection, $data) {

    $postData = [...];
    $headers = [...];

    $ch = curl_init();
    $callback = function ($ch, $dataai) {
        $connection->send($dataai);
        // echo $dataai;
        ob_flush();
        flush();
        return strlen($dataai);
    };

curl_setopt($ch, CURLOPT_URL,'xxx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
curl_exec($ch);
curl_close($ch);    
};

// Emitted when connection closed
$ws_worker->onClose = function ($connection) {
    echo "Connection closed\n";
};

// Run worker
Worker::runAll();

报错信息

New connection
PHP Warning:  Undefined variable $connection in /www/wwwroot/webman/webman/start.php on line 36
780 1 0
1个回答

2548a
    $callback = function ($ch, $dataai) use ($connection){
        $connection->send($dataai);
        // echo $dataai;
        ob_flush();
        flush();
        return strlen($dataai);
    };

改成这样

年代过于久远,无法发表回答
×
🔝