PHP code example of ollyxar / websockets
1. Go to this page and download the library: Download ollyxar/websockets library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ollyxar / websockets example snippets
use Generator;
use Ollyxar\LaravelAuth\FileAuth;
use Ollyxar\WebSockets\{
Frame,
Handler as BaseHandler,
Dispatcher
};
class MyHandler extends BaseHandler
{
/**
* MyHandler constructor.
* @param $server
* @param $master
*/
public function __construct($server, $master)
{
parent::__construct($server, $master);
echo "I'm: #{$this->pid}\n";
}
/**
* @param $client
* @return Generator
*/
protected function onConnect($client): Generator
{
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::async($this->broadcast(Frame::encode(json_encode([
'type' => 'system',
'message' => "User {$clientNumber} disconnected."
]))));
}
/**
* @param string $message
* @param int $socketId
* @return Generator
*/
protected function onClientMessage(string $message, int $socketId): Generator
{
$message = json_decode($message);
if (!empty($message)) {
$userName = $message->name;
$userMessage = $message->message;
$response = Frame::encode(json_encode([
'type' => 'usermsg',
'name' => $userName,
'message' => $userMessage
]));
yield Dispatcher::async($this->broadcast($response));
}
}
}
/**
* Use this method for custom user validation
*
* @param array $headers
* @param $socket
* @return bool
*/
protected function validateClient(array $headers, $socket): bool
{
return true;
}
/**
* Lets start our server
*/
(new Server('0.0.0.0', 2083, 6, true))
->setCert()
->setPassPhrase()
->setHandler(MyHandler::class)
->run();
Logger::enable();
use Ollyxar\WebSockets\Server as WServer;
use Ollyxar\WebSockets\Frame;
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_connect($socket, WServer::$connector);
$data = new stdClass();
$data->type = 'system';
$data->message = 'hello World!';
$msg = Frame::encode(json_encode($data));
socket_write($socket, $msg);
socket_close($socket);
bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
bash
php composer.phar