https://github.com/thenlabs/websocket-server
An asynchronous WebSocket server written in PHP.
https://github.com/thenlabs/websocket-server
php php-library websocket websocket-server websocket-servers websockets
Last synced: 4 months ago
JSON representation
An asynchronous WebSocket server written in PHP.
- Host: GitHub
- URL: https://github.com/thenlabs/websocket-server
- Owner: thenlabs
- License: mit
- Created: 2021-10-18T21:40:32.000Z (over 4 years ago)
- Default Branch: 1.0
- Last Pushed: 2022-03-26T11:43:01.000Z (about 4 years ago)
- Last Synced: 2025-07-30T21:41:30.805Z (11 months ago)
- Topics: php, php-library, websocket, websocket-server, websocket-servers, websockets
- Language: PHP
- Homepage:
- Size: 343 KB
- Stars: 4
- Watchers: 0
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# WebSocketServer
An asynchronous WebSocket server written in PHP.
>If you like this project gift us a ⭐.
## Installation.
$ composer require thenlabs/websocket-server 1.0.x-dev
>This project has not a stable version yet.
## Usage.
In the `example` directory exists a demo project which implements a bare chat server.
The `example/MyChatServer.php` file contain the class which, like you can see, implements the logic of the server through an event system.
```php
getRequest();
$nickname = explode('/', $request->getRequestUri())[1];
// notify to the connected users previously.
foreach ($this->users as $user) {
$user->send("User '{$nickname}' has connected.");
}
// add the new user to the list.
$this->users[$nickname] = $event->getConnection();
}
public function onMessage(MessageEvent $event): void
{
$senderUser = $event->getConnection();
$senderNick = array_search($senderUser, $this->users);
$message = $event->getMessage();
// send the message to the other users.
foreach ($this->users as $user) {
if ($user !== $senderUser) {
$user->send("{$senderNick}: {$message}");
}
}
}
public function onClose(CloseEvent $event): void
{
$user = $event->getConnection();
$nickname = array_search($user, $this->users);
// notify to the other users.
foreach ($this->users as $otherUser) {
if ($otherUser !== $user) {
$otherUser->send("The user {$nickname} has disconnected.");
}
}
unset($this->users[$nickname]);
}
}
```
The `example/start-server.php` file contains the script which starts the server.
```php
$argv[1] ?? '127.0.0.1',
'port' => $argv[2] ?? 9090,
];
$server = new MyChatServer($config);
$server->start();
```
This file should be executed as next:
$ php example/start-server.php
In order to test the example, we can use the `example/index.html` file which contains three clients which can be used like it's shown next:

## Development.
### Running the tests.
Start the selenium server.
$ java -jar path/to/selenium-server-standalone-x.y.z.jar
Run [PyramidalTests](https://github.com/thenlabs/pyramidal-tests).
$ ./vendor/bin/pyramidal