OpenSwoole\Http\Response->recv()

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

Declaration

<?php OpenSwoole\Http\Response->recv(float $timeout = 0): OpenSwoole\WebSocket\Frame|false|string

Parameters

timeout

Timeout in seconds. With 0 the read timeout of the socket is used.

Return

Returns an OpenSwoole\WebSocket\Frame object (an OpenSwoole\WebSocket\CloseFrame for a close frame). Returns an empty string when the peer closed the connection, and false on error or timeout, check OpenSwoole\Util::getLastErrorCode().

Description

Receive the next WebSocket frame on a connection that was upgraded with upgrade(). The current coroutine is suspended until a complete frame has arrived. Compressed frames are decompressed when WebSocket compression was accepted in the handshake. The fd property of the returned frame is set to the socket file descriptor.

Calling recv() before a successful upgrade() returns false with the warning fd[...] is not a websocket conncetion.

This method is for a response bound to a coroutine socket, created with OpenSwoole\Http\Response::create([$socket, $request]). For a OpenSwoole\Http\Server use the OpenSwoole\WebSocket\Server instead.

Example

<?php
use OpenSwoole\Coroutine\Socket;
use OpenSwoole\Http\Request;
use OpenSwoole\Http\Response;
use OpenSwoole\WebSocket\Server as WebSocketServer;

co::run(function()
{
    $server = new Socket(AF_INET, SOCK_STREAM, 0);
    $server->bind("127.0.0.1", 9502);
    $server->listen(128);

    while ($conn = $server->accept()) {
        go(function() use ($conn)
        {
            // read and parse the HTTP request
            $request = Request::create([]);
            while (!$request->isCompleted()) {
                $data = $conn->recv();
                if ($data === "" || $data === false || $request->parse($data) === false) {
                    $conn->close();
                    return;
                }
            }

            $response = Response::create([$conn, $request]);
            if (!$response->upgrade()) {
                return;
            }

            while (true) {
                $frame = $response->recv(60);
                if ($frame === "" || $frame === false || $frame->opcode === WebSocketServer::WEBSOCKET_OPCODE_CLOSE) {
                    break;
                }
                $response->push("echo: {$frame->data}");
            }
            $response->close();
        });
    }
});
Last updated on November 20, 2026