Skip to content

Commit

Permalink
Non-blocking-io (more efficient version) is a master now.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex committed Mar 9, 2018
1 parent 35f5750 commit 25f7743
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 14 deletions.
60 changes: 50 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ Simple and multifunctional PHP WebSocket server

![chat](https://i.imgur.com/7M9LhTD.jpg)

#### Performance
![ollyxar websockets performance](https://ollyxar.com/img/blog/wss.png)

## Installing WebSockets

The recommended way to install WebSockets is through
[Composer](http://getcomposer.org).
The recommended way to install WebSockets is through [Composer](http://getcomposer.org).

```bash
# Install Composer
Expand All @@ -37,16 +39,18 @@ require 'vendor/autoload.php';

## Simple WebSocket server

### MyHandler.php

```php
use Generator;
use Ollyxar\LaravelAuth\FileAuth;
use Ollyxar\WebSockets\{
Frame,
Worker,
Handler as BaseHandler,
Dispatcher
};

class MyHandler extends Handler
class MyHandler extends BaseHandler
{
/**
* MyHandler constructor.
Expand All @@ -65,53 +69,89 @@ class MyHandler extends Handler
*/
protected function onConnect($client): Generator
{
yield Dispatcher::make($this->sendToAll(WFrame::encode(json_encode([
yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
'type' => 'system',
'message' => 'User {' . (int)$client . '} Connected.'
]))));
}

/**
* @param $clientNumber
* @return Generator
*/
protected function onClose($clientNumber): Generator
{
yield Dispatcher::make($this->sendToAll(WFrame::encode(json_encode([
yield Dispatcher::async($this->broadcast(Frame::encode(json_encode([
'type' => 'system',
'message' => "User {$clientNumber} disconnected."
]))));
}

/**
* @param string $message
* @param int $socketId
* @return Generator
*/
protected function onDirectMessage(string $message): Generator
protected function onClientMessage(string $message, int $socketId): Generator
{
$message = json_decode($message);
$userName = $message->name;
$userMessage = $message->message;

$response = WFrame::encode(json_encode([
$response = Frame::encode(json_encode([
'type' => 'usermsg',
'name' => $userName,
'message' => $userMessage
]));

yield Dispatcher::make($this->sendToAll($response));
yield Dispatcher::async($this->sendToAll($response));
}
}
```

### User validation

Base `Handler` has own method to validate user to be logged in. By default it is always return true. You should provide your own implementation of method to authorize users.

```php
/**
* Use this method for custom user validation
*
* @param array $headers
* @param $socket
* @return bool
*/
protected function validateClient(array $headers, $socket): bool
{
return true;
}
```

### ws-server.php

```php
/**
* Lets start our server
*/
(new WServer('0.0.0.0', 2083, 6, true))
(new Server('0.0.0.0', 2083, 6, true))
->setCert()
->setPassPhrase()
->setHandler(MyHandler::class)
->run();
```


### Realtime testing (logging)

The server has internal logger that can output info into console.
All that you need is just to enable logging before launching server.

```php
Logger::enable();
```

![output logging](https://i.imgur.com/HaukgbL.jpg)

### Communicate with server outside the wss protocol

```php
Expand Down
13 changes: 10 additions & 3 deletions src/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function __construct($server, $master)
* @param bool $global
* @return Generator
*/
protected function sendToAll(string $msg, bool $global = true): Generator
protected function broadcast(string $msg, bool $global = true): Generator
{
Logger::log('worker', $this->pid, 'send to all: ', $msg);

Expand Down Expand Up @@ -165,6 +165,13 @@ protected function listenSocket(): Generator
yield Dispatcher::async($this->listenSocket());
}

/**
* Use this method for custom user validation
*
* @param array $headers
* @param $socket
* @return bool
*/
protected function validateClient(array $headers, $socket): bool
{
return true;
Expand Down Expand Up @@ -218,7 +225,7 @@ abstract protected function onClose($clientNumber): Generator;
*/
protected function onClientMessage(string $message, int $socketId): Generator
{
yield Dispatcher::async($this->sendToAll(Frame::encode($message)));
yield Dispatcher::async($this->broadcast(Frame::encode($message)));
}

/**
Expand All @@ -229,7 +236,7 @@ protected function onClientMessage(string $message, int $socketId): Generator
*/
protected function onMasterMessage(string $message): Generator
{
yield Dispatcher::async($this->sendToAll(Frame::encode($message), false));
yield Dispatcher::async($this->broadcast(Frame::encode($message), false));
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,17 @@ public static function log($speakerType, $speakerId, $message, $raw = ''): void
}

$log = "\033[1;37m";

try {
$log .= \DateTime::createFromFormat('U.u', microtime(true))->format("i:s:u");
} catch (\Throwable $exception) {
$log .= 'cannot get current time. God damn fast!';
}

$log .= "\033[0m ";
$log .= $speaker . " ";
$log .= "\033[1;32m" . $message . "\033[0m ";
$log .= "\033[42m" . $raw . "\033[0m\n";
echo $log;
print $log;
}
}
4 changes: 4 additions & 0 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ private function makeSocket(): void
$this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);

$this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);

chmod(static::$connector, 0777);

if (!$this->socket) {
Expand Down Expand Up @@ -115,6 +116,7 @@ private function spawn(): array
public function setHandler(string $handler): self
{
$this->handler = $handler;

return $this;
}

Expand All @@ -127,6 +129,7 @@ public function setHandler(string $handler): self
public function setCert(string $cert = '/etc/nginx/conf.d/wss.pem'): self
{
$this->cert = $cert;

return $this;
}

Expand All @@ -139,6 +142,7 @@ public function setCert(string $cert = '/etc/nginx/conf.d/wss.pem'): self
public function setPassPhrase(string $passPhrase = 'abracadabra'): self
{
$this->passPhrase = $passPhrase;

return $this;
}

Expand Down

0 comments on commit 25f7743

Please sign in to comment.