Compare commits

...

7 Commits

11 changed files with 143 additions and 79 deletions

View File

@ -1,26 +1,31 @@
# ReactPHP WebSockets
This is a library that implements WebSocket support on top of ReactPHPs HttpServer. In the process, the underlaying request and endpoint info is made available to your code. What happens next is up to you.
## Missing Features
This library is under development, and should not be used in any projects yet. The API and implementation may change in the future, and some features are still not implemented, or work in progress:
* Timeouts -- Disconnect the client on ping/pong timeout, and optionally on inactivity/idle.
* Error Handling -- Protocol errors should close the connection etc.
* Exceptions -- Exceptions should be thrown when relevant errors are encountered, such as bad encoding or data.
* Fragmented Messages -- Sending and receiving messages fragmented over multiple frames need work.
## Installing
Install using composer:
```shell
$ composer require noccylabs/react-websocket
$ composer require noccylabs/react-websocket:^0.1.0
```
## Why not Ratchet?
Note that you may need additional permissions to be able to access the repository. If so, clone it locally:
Ratchet is great! I've used Ratchet in the past, and it is a fantastic piece of code. It is however more application-centered, which means it doesn't do events and all that beautiful magic we've come to love ReactPHP for.
TL;DR - If you need to build an application with neatly wrapped classes without caring to much about the internals, go with Ratchet. If you want to work with websockets in the same way you work with sockets in ReactPHP, go with this library.
## Missing Features
The following features are missing, or work in progress:
* Idle timeout and ping timeout
* Protocol errors should close with error codes
* Exceptions
```shell
$ git clone https://dev.noccylabs.info/noccy/react-websocket ~/react-websocket
$ composer config repositories.react-websocket vcs ~/react-websocket
$ composer require noccylabs/react-websocket:^0.1.0 # ^0.1.0 or @dev
```
## Server

5
doc/ObjectUserdata.md Normal file
View File

@ -0,0 +1,5 @@
# Object UserData
There is no support for userdata on `WebSocketInterface`, `WebSocketConnection` or `ConnectionGroup`.
The rationale for this is that the connections can be easily managed using `SplObjectStorage` to link to a data object. Similarly, for groups, the names should be unique and can be used for lookups.

View File

@ -10,25 +10,34 @@ use React\Http\Message\Response;
use React\Promise\Promise;
use React\Socket\SocketServer;
// The middleware is at the core, as it intercepts and breaks out the websocket
// connections received by the HttpServer.
$websockets = new WebSocketMiddleware();
// The 'connection' handler works like expected. You can't however write any data
// to the client yet, as the websocket streams have not yet been returned.
$websockets->on('connection', function (WebSocketInterface $websocket) {
// This just echoes text received, unless the websocket is part of a group.
// In this case the message is sent to all websockets in the group.
$websocket->on('text', function ($text) use ($websocket) {
// Send a message with the group name starting with '#' to join a group.
if (str_starts_with($text, '#')) {
$websocket->setGroup(substr($text,1));
$websocket->write("joined group {$text}");
} else {
// Echo back if not in group, send to group otherwise
if (!$websocket->getGroup())
$websocket->write($text);
else
foreach ($websocket->getGroup() as $member) {
foreach ($websocket->getGroup() as $member)
$member->write($text);
}
}
});
});
// Create the server with our middleware chain:
// error handler -> websocket handler -> http handler
$server = new HttpServer(
$websockets,
// Error handler
function (ServerRequestInterface $request, callable $next) {
$promise = new Promise(function ($resolve) use ($next, $request) {
$resolve($next($request));
@ -39,11 +48,14 @@ $server = new HttpServer(
)->withStatus(Response::STATUS_INTERNAL_SERVER_ERROR);
});
},
// WebSocket handler
$websockets,
// HTTP handler
function (ServerRequestInterface $request) {
return Response::plaintext("Hello world!");
}
);
// Everything else is as expected!
$socket = new SocketServer("tcp://0.0.0.0:8000");
$server->listen($socket);
$server->listen($socket);

View File

@ -1,28 +0,0 @@
<?php
namespace NoccyLabs\React\WebSocket\Debug;
trait HexDumpTrait
{
private function hexdump($data): void
{
printf("_____ *%4d\n", strlen($data));
$rows = str_split($data, 16);
$offs = 0;
foreach ($rows as $row) {
$h = []; $a = [];
for ($n = 0; $n < 16; $n++) {
if ($n < strlen($row)) {
$h[] = sprintf("%02x%s", ord($row[$n]), ($n==7)?" ":" ");
$a[] = sprintf("%s%s", (ctype_print($row[$n])?$row[$n]:"."), ($n==7)?" ":"");
} else {
$h[] = (($n==7)?" ":" ");
$a[] = (($n==7)?" ":" ");
}
}
printf("%04x | %s | %s\n", 16 * $offs++, join("", $h), join("", $a));
}
}
}

View File

@ -46,11 +46,19 @@ class ConnectionGroup implements EventEmitterInterface, IteratorAggregate, Count
return count($this->connections);
}
/**
*
* @return \Traversable<int,WebSocketInterface>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->connections);
}
/**
*
* @return WebSocketInterface[]
*/
public function getAll(): array
{
return $this->connections;
@ -70,6 +78,10 @@ class ConnectionGroup implements EventEmitterInterface, IteratorAggregate, Count
}
}
/**
*
* @return void
*/
public function closeAll(string $reason, int $code=1001)
{
foreach ($this->connections as $connection) {

View File

@ -18,6 +18,7 @@ class WebSocketConnection implements WebSocketInterface
{
use EventEmitterTrait;
// TODO maybe move constants to WebSocketProtocol?
const OP_CONTINUATION = 0x0;
const OP_FRAME_TEXT = 0x1;
const OP_FRAME_BINARY = 0x2;
@ -58,10 +59,7 @@ class WebSocketConnection implements WebSocketInterface
$this->groupManager = $groupManager;
$this->inStream->on('data', $this->onWebSocketData(...));
$this->inStream->on('close', function () {
$this->close();
$this->emit('close', []);
});
$this->inStream->on('close', $this->close(...));
}
private function onWebSocketData($data)
@ -79,15 +77,15 @@ class WebSocketConnection implements WebSocketInterface
} else {
$this->buffer .= $payload;
}
// Break out to avoid processing partial messages
return;
}
if ($final) {
if ($this->bufferedOp !== null) {
$payload = $this->buffer . $payload;
$this->buffer = null;
if ($this->bufferedOp !== null) {
$opcode = $this->bufferedOp;
$this->bufferedOp = null;
}
$opcode = $this->bufferedOp;
$this->bufferedOp = null;
}
switch ($opcode) {
@ -223,19 +221,33 @@ class WebSocketConnection implements WebSocketInterface
/**
* {@inheritDoc}
*
* @see writeBinary() to write binary frames as opposed to text frames.
*/
public function write($data)
{
return $this->send(self::OP_FRAME_TEXT, $data);
}
/**
* Write binary frames.
*
* @param string $data
* @return bool
*/
public function writeBinary($data)
{
return $this->send(self::OP_FRAME_BINARY, $data);
}
/**
* Encode and send a frame.
*
* @param int $opcode
* @param string $data
* @param bool $final
* @param bool $masked
* @return bool
*/
public function send(int $opcode, string $data, bool $final = true, bool $masked = false)
{
@ -247,9 +259,7 @@ class WebSocketConnection implements WebSocketInterface
'masked' => $masked
]);
$this->outStream->write($frame);
return true;
return $this->outStream->write($frame);
}
/**
@ -257,15 +267,17 @@ class WebSocketConnection implements WebSocketInterface
*/
public function close()
{
// TODO send close
$this->outStream->close();
$this->inStream->close();
// TODO emit close event
$this->emit('close', []);
}
public function closeWithReason(string $reason, int $code=1000)
/**
* {@inheritDoc}
*/
public function closeWithReason(string $reason, int $code=1000): void
{
// TODO send close
$payload = chr(($code >> 8) & 0xFF) . chr($code & 0xFF) . $reason;
$this->send(self::OP_CLOSE, $payload);
}
@ -275,7 +287,7 @@ class WebSocketConnection implements WebSocketInterface
*/
public function end($data = null)
{
// TODO implement me
}
}

View File

@ -16,15 +16,46 @@ interface WebSocketInterface extends ConnectionInterface
const EVENT_GROUP_JOIN = 'join';
const EVENT_GROUP_LEAVE = 'leave';
/**
* Close the connection with a reason and code.
*
* @param string $reason
* @param int $code
* @return void
*/
public function closeWithReason(string $reason, int $code=1000): void;
public function setGroup(?string $name): void;
public function getGroupName(): ?string;
public function getGroup(): ?ConnectionGroup;
public function closeWithReason(string $reason, int $code=1000);
/**
* Get the initial HTTP request sent to the server.
*
* @return ServerRequestInterface
*/
public function getServerRequest(): ServerRequestInterface;
}
/**
* Assign this connection to a connection group. If the connection is already
* part of a group, it will leave the current group before joining the new
* group.
*
* @param null|string $name The group name to join
* @return void
*/
public function setGroup(?string $name): void;
/**
* Get the current connection group.
*
* @see getGroupName() if you want the name of the group.
*
* @return null|ConnectionGroup
*/
public function getGroup(): ?ConnectionGroup;
/**
* Get the name of the current connection group
*
* @return null|string
*/
public function getGroupName(): ?string;
}

View File

@ -18,6 +18,8 @@ class WebSocketMiddleware implements EventEmitterInterface
const MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const VERSION = 13;
use EventEmitterTrait;
private GroupManager $groupManager;
@ -32,7 +34,7 @@ class WebSocketMiddleware implements EventEmitterInterface
public function addRoute(string $path, callable $handler, array $allowedOrigins=[]): void
{
// TODO implement or remove
}
public function __invoke(ServerRequestInterface $request, callable $next)
@ -62,12 +64,15 @@ class WebSocketMiddleware implements EventEmitterInterface
$this->emit(self::EVENT_CONNECTION, [ $websocket ]);
//});
// TODO would it be possible for the 'connection' event to set additional response headers to be sent here?
// For example, to send back Sec-WebSocket-Protocol header.
return new Response(
Response::STATUS_SWITCHING_PROTOCOLS,
array(
'Upgrade' => 'websocket',
'Connection' => 'upgrade',
'Sec-WebSocket-Accept' => $handshakeResponse
'Sec-WebSocket-Accept' => $handshakeResponse,
'Sec-WebSocket-Version' => self::VERSION
),
$stream
);

View File

@ -111,7 +111,7 @@ class WebSocketProtocol
* payload (string) - the payload
*
* @param string $frame The frame data to decode
* @return array The decoded frame
* @return array<string,mixed> The decoded frame
*/
public function decode(string $frame): array
{
@ -125,6 +125,7 @@ class WebSocketProtocol
$byte0 = ord($frame[0]);
$decoded['final'] = !!($byte0 & 0x80);
$decoded['opcode'] = $byte0 & 0x0F;
// Peek at the second byte, holding mask bit and len
$byte1 = ord($frame[1]);
$decoded['masked'] = $masked = !!($byte1 & 0x80);
@ -146,14 +147,16 @@ class WebSocketProtocol
$header += 4;
}
// Now for the masking
// Now for the masking, if present.
if ($masked) {
$mask = substr($frame, $header, 4);
$header += 4;
}
// Extract and unmask payload
// Extract the payload, and unmask it if needed. The mask() function handles
// both masking and unmasing as the algorithm uses xor.
$payload = substr($frame, $header, $len);
// TODO check that extracted payload len equals expected len
if ($masked) {
$payload = $this->mask($payload, $mask);
$decoded['mask'] = $mask;
@ -174,14 +177,17 @@ class WebSocketProtocol
*/
private function mask(string $payload, string $mask): string
{
// Unpack the payload and mask into byte values
$payloadData = array_map("ord", str_split($payload,1));
$maskData = array_map("ord", str_split($mask,1));
// TODO check that mask len==4
$unmasked = [];
for ($n = 0; $n < count($payloadData); $n++) {
$unmasked[] = $payloadData[$n] ^ $maskData[$n % 4];
}
// Return the masked byte values packed into a string
return join("", array_map("chr", $unmasked));
}

View File

@ -3,11 +3,14 @@
namespace NoccyLabs\React\WebSocket\Group;
use NoccyLabs\React\WebSocket\WebSocketConnection;
use NoccyLabs\React\WebSocket\WebSocketProtocol;
use PHPUnit\Framework\Attributes\CoversClass;
use React\Http\Message\ServerRequest;
use React\Stream\ThroughStream;
#[CoversClass(ConnectionGroup::class)]
#[CoversClass(WebSocketConnection::class)]
#[CoversClass(WebSocketProtocol::class)]
class ConnectionGroupTest extends \PHPUnit\Framework\TestCase
{
@ -49,4 +52,4 @@ class ConnectionGroupTest extends \PHPUnit\Framework\TestCase
$this->assertEquals(3, count($r));
}
}
}

View File

@ -6,6 +6,7 @@ use PHPUnit\Framework\Attributes\CoversClass;
use React\Http\Message\ServerRequest;
#[CoversClass(WebSocketMiddleware::class)]
#[CoversClass(WebSocketConnection::class)]
class WebSocketMiddlewareTest extends \PHPUnit\Framework\TestCase
{
@ -54,4 +55,4 @@ class InvokableDummy
public function test()
{
}
}
}