Make websockets.php able to proceed blocking treatments

This commit is contained in:
Benjamin Loison 2023-02-07 01:22:26 +01:00
parent 1fe92ec2d0
commit a116b29df9
Signed by: Benjamin_Loison
SSH Key Fingerprint: SHA256:BtnEgYTlHdOg1u+RmYcDE0mnfz1rhv5dSbQ2gyxW8B8

View File

@ -2,6 +2,8 @@
use Ratchet\MessageComponentInterface; use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface; use Ratchet\ConnectionInterface;
use React\EventLoop\LoopInterface;
use React\EventLoop\Timer\Timer;
// Make sure composer dependencies have been installed // Make sure composer dependencies have been installed
require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/vendor/autoload.php';
@ -12,10 +14,12 @@ require __DIR__ . '/vendor/autoload.php';
class MyChat implements MessageComponentInterface class MyChat implements MessageComponentInterface
{ {
protected $clients; protected $clients;
private $loop;
public function __construct() public function __construct(LoopInterface $loop)
{ {
$this->clients = new \SplObjectStorage(); $this->clients = new \SplObjectStorage();
$this->loop = $loop;
} }
public function onOpen(ConnectionInterface $conn) public function onOpen(ConnectionInterface $conn)
@ -26,6 +30,10 @@ class MyChat implements MessageComponentInterface
public function onMessage(ConnectionInterface $from, $msg) public function onMessage(ConnectionInterface $from, $msg)
{ {
$from->send($msg); $from->send($msg);
$this->loop->addTimer(Timer::MIN_INTERVAL * 10, function() use ($from) {
sleep(5);
$from->send('Proceeded!');
});
} }
public function onClose(ConnectionInterface $conn) public function onClose(ConnectionInterface $conn)
@ -39,7 +47,9 @@ class MyChat implements MessageComponentInterface
} }
} }
$loop = \React\EventLoop\Factory::create();
// Run the server application through the WebSocket protocol on port 4430 // Run the server application through the WebSocket protocol on port 4430
$app = new Ratchet\App('crawler.yt.lemnoslife.com', 4430); $app = new Ratchet\App('crawler.yt.lemnoslife.com', 4430, '127.0.0.1', $loop);
$app->route('/websocket', new MyChat(), array('*')); $app->route('/websocket', new MyChat($loop), array('*'));
$app->run(); $app->run();