Swoole HTTP Response

The object of Swoole\HTTP\Request class contains the information of a HTTP response..

You can use the following methods to access the HTTP response and send back data to HTTP client.

Methods

  • Swoole\HTTP\Response->header
  • Swoole\HTTP\Response->cookie
  • Swoole\HTTP\Response->status
  • Swoole\HTTP\Response->gzip
  • Swoole\HTTP\Response->write
  • Swoole\HTTP\Response->sendfile
  • Swoole\HTTP\Response->end
  • Swoole\HTTP\Response->trailer
  • Swoole\HTTP\Response->detach

    Example

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

    <?php
    $http->on('request', function ($request, $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);
        }
    });