Romanovich095

Socket.IO with PHP

Mar 25th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.41 KB | None | 0 0
  1. <?php
  2. namespace App\Controller\Component;
  3.  
  4. use Cake\Controller\Component;
  5. use Cake\Core\Configure;
  6. use Cake\Log\Log;
  7. use ElephantIO\Client as Client;
  8. use ElephantIO\Engine\SocketIO\Version1X as Version;
  9. use ElephantIO\Exception\ServerConnectionFailureException;
  10.  
  11. /**
  12.  * Class SocketComponent
  13.  * @package App\Controller\Component
  14.  */
  15. class SocketComponent extends Component
  16. {
  17.  
  18.     /**
  19.      * Sockets client
  20.      *
  21.      * @var Client
  22.      */
  23.     private $_sender;
  24.  
  25.     /**
  26.      * Sockets connection url
  27.      *
  28.      * @var string
  29.      */
  30.     private $_url;
  31.  
  32.     /**
  33.      * Building up a connection to socket
  34.      *
  35.      * @param array $config
  36.      */
  37.     public function initialize(array $config)
  38.     {
  39.         try {
  40.             $this->_url = Configure::read('socket_url');
  41.             $this->_sender = new Client(new Version($this->_url));
  42.             $this->_sender->initialize();
  43.         } catch (\Exception $e) {
  44.             Log::warning('Cannot connect to socket server');
  45.         }
  46.     }
  47.  
  48.     /**
  49.      * Sending data
  50.      *
  51.      * @param string $key
  52.      * @param array $data
  53.      */
  54.     public function emit($key = 'broadcast', $data = [])
  55.     {
  56.         Log::info($data + ['user' => $key]);
  57.         $this->_sender->emit($key, (array)$data);
  58.     }
  59.  
  60.     /**
  61.      * Closing connection
  62.      */
  63.     public function __destruct()
  64.     {
  65.         $this->_sender->close();
  66.     }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment