OpenSwoole\Http\Response->write()

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

Declaration

<?php OpenSwoole\Http\Response->write(string $data): bool

Parameters

data

Data to write to the HTTP body. The max length of the data by default is 2M. Controlled by buffer_output_size

Return

bool

If successful, true is returned otherwise false

Description

Send data back to the HTTP client in a segmented chunk, the write() method uses HTTP Chunk to send content back to the browser. This feature uses Transfer-Encoding to transfer segmented messages or payload body data between a client and server, data can be sent in a series of chunks.

If you have already performed calls to write() and then call $response->end() afterwards, it will send a chunk of length 0 to end data transmission with the client.

This method must be called before the $response->end() method.

Since v4.10.0, you can use this method to send HTTP2 DATA frame or push data to clients.

Example

<?php

$server->on('Request', function(OpenSwoole\Server\Request $request, OpenSwoole\Server\Response $response)
{
  $response->write('Hello ');
  $response->write('World!');

  // Optional, but will set the content length to 0 and end the response
  $response->end();
});

Notes

  • If you want to send a complete HTTP body back to the client all at once, the $response->end method might be more useful.

  • Adjust max data size by changing buffer_output_size, the default is 2M

HTTP2 SSE example

<?php
$http = new OpenSwoole\HTTP\Server("0.0.0.0", 9501, OpenSwoole\Server::SIMPLE_MODE, OpenSwoole\Constant::SOCK_TCP | OpenSwoole\Constant::SSL);
$http->set([
    'open_http2_protocol' => 1,
    'enable_coroutine' => true,
    'ssl_cert_file' => __DIR__ . '/example.com+4.pem',
    'ssl_key_file' => __DIR__ . '/example.com+4-key.pem',
]);

$http->on('request', function (OpenSwoole\HTTP\Request $request, OpenSwoole\HTTP\Response $response) {

    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Content-Type', 'text/event-stream');
    $response->header('Cache-Control', 'no-cache');
    $response->header('X-Accel-Buffering', 'no');

    while(1) {
        $response->write("event: ping\n\n");
        $r = $response->write("data: {\"time\": \"" . date(DATE_ISO8601) . "\"}\n\n");
        if(!$r) return;
        co::sleep(1);
    }
    // never reach
    $response->end('DONE');
});

$http->start();

Client side:

<script type="text/javascript">
const eventSrc = new EventSource("https://localhost:9501/");
eventSrc.addEventListener('open', function (event) {
  console.log(event.type);
});

eventSrc.addEventListener('message', function (event) {

  console.log(event.type);
  console.log(event.data);

});
</script>
Last updated on September 20, 2022