75 lines
2.3 KiB
PHP
75 lines
2.3 KiB
PHP
<?php
|
|
require '../../vendor/autoload.php'; // Include Ratchet library
|
|
|
|
require_once 'fixed/config/private.php'; // Include your database configuration
|
|
|
|
use Ratchet\MessageComponentInterface;
|
|
use Ratchet\ConnectionInterface;
|
|
use Ratchet\Server\IoServer;
|
|
use Ratchet\Http\HttpServer;
|
|
use Ratchet\WebSocket\WsServer;
|
|
|
|
class DataUpdates implements MessageComponentInterface {
|
|
protected $clients;
|
|
protected $pdo; // Database connection
|
|
|
|
public function __construct() {
|
|
global $host_db,$name_db,$user_db,$pass_db;
|
|
$this->clients = new \SplObjectStorage();
|
|
$this->pdo = new PDO("mysql:host=" . $host_db . ";dbname=" . $name_db, $user_db, $pass_db);
|
|
}
|
|
|
|
public function onOpen(ConnectionInterface $conn) {
|
|
// Add the new connection to the clients list
|
|
$this->clients->attach($conn);
|
|
echo "new connection ({$conn->resourceId})\n";
|
|
echo 'hi';
|
|
|
|
// Retrieve initial data from the database and send it to the client
|
|
$initialData = $this->fetchDataFromDatabase();
|
|
$conn->send(json_encode($initialData));
|
|
}
|
|
|
|
public function onMessage(ConnectionInterface $conn, $msg) {
|
|
// Handle incoming messages (if any)
|
|
}
|
|
|
|
public function onClose(ConnectionInterface $conn) {
|
|
// Remove the connection when the client disconnects
|
|
$this->clients->detach($conn);
|
|
echo "dicc connection ({$conn->resourceId})\n";
|
|
}
|
|
|
|
public function onError(ConnectionInterface $conn, \Exception $e) {
|
|
echo "error connection ({$e->getMessage})\n";
|
|
// Handle errors here (e.g., log or close the connection)
|
|
$conn->close();
|
|
}
|
|
|
|
|
|
|
|
// Function to send data to all connected clients
|
|
public function sendDataToClients($data) {
|
|
foreach ($this->clients as $client) {
|
|
$client->send(json_encode($data));
|
|
}
|
|
}
|
|
|
|
// Function to fetch data from the database (customize as needed)
|
|
private function fetchDataFromDatabase() {
|
|
$stmt = $this->pdo->prepare("SELECT * FROM book LIMIT 15");
|
|
$stmt->execute();
|
|
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
}
|
|
|
|
$server = IoServer::factory(
|
|
new HttpServer(
|
|
new WsServer(
|
|
new DataUpdates()
|
|
)
|
|
),
|
|
8083 // Change the port as needed
|
|
);
|
|
|
|
$server->run(); |