WebSocketService.php 881 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Log;
  4. use ElephantIO\Client;
  5. class WebSocketService
  6. {
  7. public function emitToUser($userId, $event, $data)
  8. {
  9. try {
  10. $url = 'http://localhost:3200';
  11. $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
  12. $socketClient->initialize();
  13. $socketClient->of('/');
  14. // Emitir evento con userId para que app.js lo distribuya
  15. $socketClient->emit('laravel_emit', [
  16. 'event' => $event,
  17. 'data' => $data,
  18. 'userId' => $userId
  19. ]);
  20. $socketClient->close();
  21. return true;
  22. } catch (\Exception $e) {
  23. Log::error('WebSocket emit failed: ' . $e->getMessage());
  24. return false;
  25. }
  26. }
  27. }