0
Hi, I made a PHP Websocket with Ratchet.
The server.php is as follows:
require "../vendor/autoload.php";
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Chat;
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        8000
    );
    $server->run();
And the Chat() class is as follows:
<?php
namespace App;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
    protected $clients;
    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }
    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }
    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
        foreach ($this->clients as $client) {
            if ($from === $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }
    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
So far, so good. However, I have the notifications table in mysql, and I would like to send the client a message whenever there is a new record, in case the client is "listening" to the server until it sends an alert. How can I do that?
You want to control the customer?
– ShutUpMagda
I don’t know if that would be it. For example, I have the notifications table, I want to give a $client->send() only when the table has new records. I would have to loop running the query all the time inside Websocket?
– Wallace Magalhães
Are the table changes made by one of the users who are connected in the room? If yes, once a user executes an action that inserts a new record in the notifications table, you can select and send it to users logged in the room as a message
– Marcos Xavier
I recommend taking a look https://github.com/pmill/react-chat
– Marcos Xavier