Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to do non blocking I/O in React PHP

I am trying to insert a record inside database coming to a react socket server. I am lost on how to do my operation in a non blocking way

$loop = Factory::create();

$server = new Server('127.0.0.1:4040', $loop);
$database = new Database();

$server->on('connection', function(ConnectionInterface $conn)  use ($database) {
    $conn->write('Welcome, you can start writing your notes now...');

    $conn->on('data', function($data) use ($conn, $database) {
        $database->write($data);
        $conn->write('I am supposed to execute before database write');
    });
});

$loop->run();

The write method in database has a sleep(10) seconds before executing the sql statement. So I am expecting the next message I am supposed to.. should be printed immediately.

My expectation was that when ever there is a I/O operation, the operation will be moved to Event Table and don't block the call stack. As per the definition of event loop and non blocking.

How can I perform the same operation in non blocking way.

Thanks

like image 533
Raheel Avatar asked Apr 09 '26 02:04

Raheel


1 Answers

Hey ReactPHP core team member here. The loop expects everything to be asynchronous so putting a sleep in your $database->write($data); will block the loop. Your database connection has to utilise the event loop for it to be non-blocking. My suggestion would be to look at https://github.com/friends-of-reactphp/mysql or https://github.com/voryx/PgAsync or check the list here https://github.com/reactphp/react/wiki/Users#databases depending on your database. ReactPHP won't magically make everything non-blocking, you have to use packages that take care of that for you.

like image 153
WyriHaximus Avatar answered Apr 10 '26 15:04

WyriHaximus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!