Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurkushman committed Aug 14, 2019
2 parents 391eee5 + 1c5db4c commit 7dcc423
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,10 @@ or any other available options see - https://www.php.net/manual/en/context.php.
### BroadCasting
You may wish to broadcast messages by simply calling `broadCast` method on `Connection` object in any method of your `ServerHandler` class:
```php
$conn->broadCast('hey everybody...');
$conn->broadCast('hey everybody...');

// or to send multiple messages with 2 sec delay between them
$conn->broadCastMany(['Hello', 'how are you today?', 'have a nice day'], 2);
```

### How to test
Expand Down
22 changes: 22 additions & 0 deletions src/Components/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,28 @@ public function broadCast(string $data): void
}
}

/**
* Broadcasting many messages with delay
*
* @param array $data An array of messages (strings) sent to many clients
* @param int $delay Time in seconds to delay between messages
* @throws \Exception
*/
public function broadCastMany(array $data, int $delay = 0): void
{
foreach ($data as $message) {
foreach ($this->clients as $client) {
if (is_resource($client)) { // check if not yet closed/broken etc
fwrite($client, $this->encode($message));
}
}

if ($delay > 0) {
sleep($delay);
}
}
}

/**
* Encodes data before writing to the client socket stream
*
Expand Down
2 changes: 2 additions & 0 deletions src/Contracts/ConnectionContract.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ public function getUniqueSocketId(): int;
public function getPeerName(): string;

public function broadCast(string $data): void;

public function broadCastMany(array $data, int $delay): void;
}

0 comments on commit 7dcc423

Please sign in to comment.