src/Chat/ServerWebSocket.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Chat;
  3. use App\Chat\Chat;
  4. use Ratchet\Http\HttpServer;
  5. use Ratchet\Server\IoServer;
  6. use Ratchet\WebSocket\WsServer;
  7. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  8. use Symfony\Component\Console\Input\InputInterface;
  9. use Symfony\Component\Console\Output\OutputInterface;
  10. class ServerWebSocket extends ContainerAwareCommand
  11. {
  12.     /**
  13.      * Configure a new Command Line
  14.      */
  15.     protected function configure()
  16.     {
  17.         $this
  18.             ->setName('Project:websocket:server')
  19.             ->setDescription('Start the websocket server.');
  20.     }
  21.     protected function execute(InputInterface $inputOutputInterface $output)
  22.     {
  23.        // date_default_timezone_set("America/New_York");
  24.         header("Content-Type: text/event-stream\n\n");
  25.         
  26.         $counter rand(110);
  27.         while (1) {
  28.           // Chaque seconde, envoi d’un évènement "ping".
  29.         
  30.           echo "event: ping\n";
  31.           $curDate date(DATE_ISO8601);
  32.           echo 'data: {"time": "' $curDate '"}';
  33.           // Paire de sauts de ligne
  34.           echo "\n\n";
  35.         
  36.           // Envoie un message simple à des intervalles aléatoires.
  37.         
  38.           $counter--;
  39.         
  40.           if (!$counter) {
  41.             echo 'data: This is a message at time ' $curDate "\n\n";
  42.             $counter rand(110);
  43.           }
  44.         
  45.           ob_end_flush();
  46.           flush();
  47.           sleep(1);
  48.         }
  49.     }
  50. }