Skip to content

Commit

Permalink
#58: Fix large payload unsaved and closed conn
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman committed Jun 20, 2021
1 parent 6d3dc0f commit 9d76976
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/WebSocketServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,12 +242,17 @@ private function acceptNewClient($server, array &$readSocks): void
*/
private function messagesWorker(array $readSocks): void
{
$largePayloadData = '';
foreach ($readSocks as $kSock => $sock) {
$data = $this->decode(fread($sock, self::MAX_BYTES_READ));
if ($data !== null) {
$dataType = $data['type'];
$dataPayload = $data['payload'];

if ($data === false) { // payload is too large - waiting for remained data
$largePayloadData += $dataPayload;
}

// to manipulate connection through send/close methods via handler, specified in IConnection
$cureentConn = new Connection($sock, $this->clients);
if (empty($data) || $dataType === self::EVENT_TYPE_CLOSE) { // close event triggered from client - browser tab or close socket event
Expand All @@ -267,6 +272,11 @@ private function messagesWorker(array $readSocks): void
&& method_exists($this->handler, self::MAP_EVENT_TYPE_TO_METHODS[$dataType]);
if ($isSupportedMethod) {
try {
if (empty($largePayloadData) === false) {
$dataPayload = $largePayloadData + $dataPayload;
$largePayloadData = ''; // clear saved large payload for the next one
}

// dynamic call: onMessage, onPing, onPong
$this->handler->{self::MAP_EVENT_TYPE_TO_METHODS[$dataType]}($cureentConn, $dataPayload);
} catch (WebSocketException $e) {
Expand Down

0 comments on commit 9d76976

Please sign in to comment.