Swoole HTTP Response

The Swoole\HTTP\Response object is passed to the Request event when running a Swoole HTTP server and allows you to build a HTTP server response to the client, this object allows you to setup a response based on the current request and send data back to the client. You can set things like the headers, HTTP status, cookies, body data and files etc. This object is responsible for how the client will receive the server response.

You should not access this object via call-by-reference (use of the & symbol in PHP) because the object is destroyed afterwards and may lead to undefined object errors, only access it from the event callback, this object is only valid during the lifecycle of the server request, meaning the response object is destroyed after the request has finished.

Methods

You can use the following methods to create and form a HTTP server response which gets sent to the client:

Example

A simple Swoole PHP based SSE (server-sent events) example looks like this.

<?php
$http->on('Request', function(Swoole\Http\Request $request, Swoole\Http\Response $response)
{
    $response->header('Content-Type', 'text/event-stream');
    $response->header('Cache-Control', 'no-cache');

    $counter = rand(1, 10);

    while(true)
    {
        $data = "event: ping\n";

        $response->write($data);

        $curDate = date(DATE_ISO8601);

        $data = 'data: {"time": "' . $curDate . '"}';
        $data .= "\n\n";

        $response->write($data);

        $counter--;
        if(!$counter)
        {
           $data = 'data: This is a message at time ' . $curDate . "\n\n";
           $response->end($data);
           break;
        }

        co::sleep(1);
    }
});

Notes

  • If a HTTP response has not been set, no message, no body data, then the server will simply send back $response->end('')