Skip to content

Commit

Permalink
ws response
Browse files Browse the repository at this point in the history
  • Loading branch information
walkor committed Jun 11, 2023
1 parent ed306de commit 01f43d8
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/Protocols/Ws.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Throwable;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\ConnectionInterface;
use Workerman\Protocols\Http\Response;
use Workerman\Timer;
use Workerman\Worker;
use function base64_encode;
Expand Down Expand Up @@ -422,10 +423,12 @@ public static function dealHandshake(string $buffer, AsyncTcpConnection $connect
// handshake complete
$connection->context->handshakeStep = 2;
$handshakeResponseLength = $pos + 4;
$buffer = substr($buffer, 0, $handshakeResponseLength);
$response = static::parseResponse($buffer);
// Try to emit onWebSocketConnect callback.
if (isset($connection->onWebSocketConnect)) {
try {
($connection->onWebSocketConnect)($connection, substr($buffer, 0, $handshakeResponseLength));
($connection->onWebSocketConnect)($connection, $response);
} catch (Throwable $e) {
Worker::stopAll(250, $e);
}
Expand All @@ -452,4 +455,29 @@ public static function dealHandshake(string $buffer, AsyncTcpConnection $connect
return 0;
}

/**
* Parse response.
*
* @param string $buffer
* @return Response
*/
protected static function parseResponse(string $buffer): Response
{
[$http_header, ] = \explode("\r\n\r\n", $buffer, 2);
$header_data = \explode("\r\n", $http_header);
[$protocol, $status, $phrase] = \explode(' ', $header_data[0], 3);
$protocolVersion = substr($protocol, 5);
unset($header_data[0]);
$headers = [];
foreach ($header_data as $content) {
// \r\n\r\n
if (empty($content)) {
continue;
}
list($key, $value) = \explode(':', $content, 2);
$value = \trim($value);
$headers[$key] = $value;
}
return (new Response())->withStatus((int)$status, $phrase)->withHeaders($headers)->withProtocolVersion($protocolVersion);
}
}

0 comments on commit 01f43d8

Please sign in to comment.