WebSocketService.php 975 B

12345678910111213141516171819202122232425262728293031323334
  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. Log::info('WebSocket emit successful', ['userId' => $userId, 'event' => $event]);
  22. return true;
  23. } catch (\Exception $e) {
  24. Log::error('WebSocket emit failed: ' . $e->getMessage());
  25. return false;
  26. }
  27. }
  28. }