Skip to content

Using grpc bidirectional streaming in swoole  #5661

@Domex777

Description

@Domex777

I try to create a simple grpc bidirectional streaming server and client for transfer messages between services, and i came across the fact that I can't start receiving a response from the server until I explicitly indicate that the message is the last one. Although I found a lot of information that the server can respond to each message gradually.

Example server and client

Server

$http = new Server('0.0.0.0', 50051, SWOOLE_BASE);
$http->set([
    "log_level" => SWOOLE_LOG_INFO,
    "trace_flags" => 0,
    "worker_num" => 1,
    "open_http2_protocol" => true
]);
$http->on('workerStart', function (Server $server) {
    echo "w s";
});

$http->on('connect', function (Server $server, int $fd, int $reactorId) {
    var_dump($server->getClientInfo($fd));
});

$http->on('request', function (Request $request, Response $response) use ($http) {
    var_dump($request);
});

$http->start();

Client

run(function () {
    $client = new Client('host.docker.internal', 50051);

    if (!$client->connect()) {
        echo "Connection failed\n";
        return;
    }
    
    $request = new Request();
    $request->pipeline = true;
    
    $request->headers = [
        'content-type' => 'application/grpc',
        'te' => 'trailers'
    ];

    $data = "test message";
    $request->data = pack('CN', 0, strlen($data)) . $data;

    $streamId = $client->send($request);
    var_dump($streamId);
    go(function () use ($client, $streamId) {
        for ($i = 0; $i < 10; $i++) {
            $data = "test message";
            $data = pack('CN', 0, strlen($data)) . $data;
            dump($client->write($streamId, $data));

            Coroutine::sleep(1);
        }
    });


    if ($streamId > 0) {
        while (true) {
            $response = $client->read(-1);
            dump($response);
            if ($response) {
                echo "Response received\n";
                var_dump($response->data);
            }
            Coroutine::sleep(1);
        }
    }

    $client->close();
});
Swoole 6
Gcc version 13.2.1 20240309 (Alpine 13.2.1_git20240309) 
PHP 8.4.1 (cli) 

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions