OpenSwoole\Coroutine\Http2\Client->write(...)

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Coroutine\Http2\Client->write(int $streamId, mixed $data, bool $end = false): bool

Parameters

streamId

The integer ID of the stream you want to send to, check the example for how to get this ID.

data

The data you want to send to the stream, data is sent as a frame, can be a string or an array. Refer to the send() method for more information on data types and when they are sent.

end

By default this is false, setting it to true will send the data and end the stream, keep it false if you still want to send data again.

Return

Returns true if everything is okay and false when there is an error. Check $client->errCode for more details.


Description

Write to the HTTP/2 stream that is open, allows you to write data to the stream.

To send more data frames to the remote server, you can call write multiple times to write data frames to the same stream.

You must first use send() and enable the pipeline option so that the stream stays open to use this method. Checkout the example below...


Example

To use the write() method we can get the streamId from our call to send():

<?php

use OpenSwoole\Http2\Request;
use OpenSwoole\Coroutine\Http2\Client;

co::run(function()
{
    // Create a new client and set options
    $client = new Client('127.0.0.1', 9518);
    $client->set(['timeout' => 2]);
    var_dump($client->connect());

    $request = new Request();
    $request->path = "/index.php";
    $request->headers = [
        'host' => "localhost",
        "user-agent" => 'Chrome/49.0.2587.3',
        'accept' => 'text/html,application/xhtml+xml,application/xml',
        'accept-encoding' => 'gzip',
    ];

    // This means we want to keep the stream open after the initial send() call
    $request->pipeline = true;
    $request->method = "POST";

    // Initiate the request and keep the stream open, using write() to send more data...
    $streamId = $client->send($request);
    $client->write($streamId, ['int' => rand(1000, 9999)]);
    $client->write($streamId, ['int' => rand(1000, 9999)]);

    // Send the final data frame and end the stream...
    $client->write($streamId, ['int' => rand(1000, 9999), 'end' => true], true);

    // Receive the response and close the client connection
    var_dump($client->recv());
    $client->close();
});

You must set $request->pipeline = true so that the stream is kept open, allowing you to send more data, remember to end the stream once you have finished with $end = true - This will close the stream connection.

Last updated on September 1, 2022