3

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

Raheel
  • 8,716
  • 9
  • 60
  • 102

1 Answers1

8

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.

WyriHaximus
  • 1,000
  • 6
  • 8