Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-26.11.1 | composer require openswoole/core:26.11.1
<?php OpenSwoole\Http\Response->upgrade(): bool
Returns true when the WebSocket handshake response was sent, otherwise false.
Upgrade the HTTP connection to a WebSocket connection. The method checks the Sec-WebSocket-Key header of the request and sends the 101 Switching Protocols handshake response with the Sec-WebSocket-Accept header. When the client offers permessage-deflate and compression is enabled, the response also accepts WebSocket compression.
If the Sec-WebSocket-Key header is missing or invalid, a 400 Bad Request response is sent and false is returned.
After a successful upgrade, use recv() to read frames, push() to send frames and close() to close the connection.
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. On a response of OpenSwoole\Http\Server, upgrade() returns false with the warning async server dose not support protocol upgrade.
<?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();
});
}
});