clients array is empty every time inside broadcast function and I ensure that instance is singleton . In onOpen and onClose functions $clients exists but why in broadcast function clients is empty class OrderWebSocketServer implements MessageComponentInterface { protected $clients; private static $instance = null; protected $copyClients=[ ]; public function __construct() { $this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->copyClients=$this->clients;
echo "Total connected clients: " . $this->clients->count() . "\n";
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
// Handle incoming messages if needed
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
// dd(self::$instance);
return self::$instance;
}
public function onClose(Connection Interface $conn)
{
echo "Total connected clients: " . count($this->clients) . "\n";
$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();
}
public function broadcast($data)
{
// Debugging: Output the number of connected clients
// echo "Broadcasting to " . $this->clients->count() . " clients\n";
echo "Total: " . count($this->copyClients) . "\n";
foreach ($this->clients as $client) {
$client->send(json_encode($data));
}
//echo "Broadcasting data: " . json_encode($data) . "\n"; // Debug output
}
}