📜 ⬆️ ⬇️

Quick start with phpDaemon based WebSocket

On Habré already have an article on this topic. But the framework has since been greatly updated and, unfortunately, the old article will most likely find it difficult to figure it out. In addition, in learning something new, the most difficult is always the beginning. Therefore, I will try to describe the start process at least in general terms.

Installation


In principle, the installation is described on the official site .
I assume that you already have PHP installed with a version at least 5.3. Therefore, I describe only the rest (using the example of FreeBSD):
  1. Install the necessary libraries for PHP from ports:

    This can be done separately:
    • php5-pcntl
      # cd /usr/ports/devel/php5-pcntl # make install clean 
    • php5-shmop
       # cd /usr/ports/devel/php5-shmop # make install clean 
    • php5-sockets
       # cd /usr/ports/net/php5-sockets # make install clean 

    either using the php5-extensions port:
     # cd /usr/ports/lang/php5-extensions # make config 

    Check off the box next to PCNTL, SHMOP and SOCKETS and install:
     # make install clean 

    In the second approach, at the end you can get an error that the port php5-extensions is already installed. However, the libraries themselves will be installed normally.
    ')
  2. Install pecl-eio :
     # cd /usr/ports/devel/pecl-eio # make install clean 


  3. Install the pecl-event :
     # cd /usr/ports/devel/pecl-event # make install clean 


  4. If git is not installed yet, set it (you can leave it unchanged):
     # cd /usr/ports/devel/git # make install clean 


  5. Install phpDaemon as stated on the site:
     # cd /usr/local # git clone git://github.com/kakserpom/phpdaemon.git # chmod +x phpdaemon/bin/phpd # ln -s /usr/local/phpdaemon/bin/phpd /usr/bin/phpd 



In principle, the installation itself is complete. Now it's worth trying the first application. To do this, take an example from the bundle - ExampleWebSocket. To do this, you need to register the configuration of our WebSocket server in the file /usr/local/phpdaemon/conf/phpd.conf :
 user www; group www; max-workers 8; min-workers 1; start-workers 1; max-idle 0; Pool:Servers\WebSocket { enable 1; listen "tcp://0.0.0.0"; listen-port 8047; privileged; } ExampleWebSocket {} 



Now we try to start our server:
 # phpd start 


Everything should go fine and in the logs (/var/log/phpdaemon.log) we should see something like the following:
 M#7964 \PHPDaemon\Core\Pool:Servers\WebSocket up. M#7964 \PHPDaemon\Core\Pool:\PHPDaemon\Servers\WebSocket\Pool up. W#7966 \PHPDaemon\Examples\ExampleWebSocket up. Spawning 1 worker(s) W#7967 \PHPDaemon\Examples\ExampleWebSocket up. 


We write the first application


I would like to offer in addition to the bundled one more example of a WebSocket application. I think an extra example will never be harmful to a new man who understands.
Immediately it should be noted that at this point in time the official documentation is very outdated. The developer promises to fix this in the future. However, you can always open the class of interest to the framework, find the method you need and figure out how it works. Most often this does not take much time: the code is intuitive.

So:
  1. Create a new file in the PHPDaemon / Applications folder called MyWebSocket.php with the following code:
     <?php namespace PHPDaemon\Applications; class MyWebSocket extends \PHPDaemon\Core\AppInstance { public $enableRPC=true; //         public $sessions=array(); //         //        public function onReady() { $appInstance = $this; //  timerTask()    5  $this->timerTask($appInstance); //       ws://site.com:8047/myws \PHPDaemon\Servers\WebSocket\Pool::getInstance()->addRoute('myws', function ($client) use ($appInstance) { $session=new MyWebSocketRoute($client, $appInstance); //   $session->id=uniqid(); //    ID $this->sessions[$session->id]=$session; //   return $session; }); } function timerTask($appInstance) { //      foreach($this->sessions as $id=>$session) { $session->client->sendFrame('This is private message to client with ID '.$id, 'STRING'); } //         ( ) $appInstance->broadcastCall('sendBcMessage', array(\PHPDaemon\Core\Daemon::$process->getPid())); //     5  \PHPDaemon\Core\Timer::add(function($event) use ($appInstance) { $this->timerTask($appInstance); $event->finish(); }, 5e6); //     } //     (     ) public function sendBcMessage($pid) { foreach($this->sessions as $id=>$session) { $session->client->sendFrame('This is broadcast message from worker #'.$pid, 'STRING'); } } } class MyWebSocketRoute extends \PHPDaemon\WebSocket\Route { public $client; public $appInstance; public $id; //   ID  public function __construct($client,$appInstance) { $this->client=$client; $this->appInstance=$appInstance; } //       public function onFrame($data, $type) { //    $this->client->sendFrame('Server receive from client #'.$this->id.' message "'.$data.'"', 'STRING'); } //        public function onFinish() { //     unset($this->appInstance->sessions[$this->id]); } } 

  2. We correct our configuration file to the following form:
     user www; group www; max-workers 8; min-workers 1; start-workers 1; max-idle 0; Pool:Servers\WebSocket { enable 1; listen "tcp://0.0.0.0"; listen-port 8047; privileged; } MyWebSocket {} 

  3. Create an HTML file on your computer with the following contents:
     <script type="text/javascript"> function add(text) { document.forms[0].b.value=text+"\n"+document.forms[0].b.value; } if("WebSocket" in window) { var timer; var ws=new WebSocket("ws://site.com:8047/myws"); ws.onopen=function() { add('Connection opened'); timer=window.setInterval(function() { var date = new Date(); var message='ping at '+date.getSeconds(); ws.send(message); add('Client sent message "'+message+'"'); }, 30000); }; ws.onmessage=function(evt) { add('Message from server: "'+evt.data+'"'); }; ws.onclose=function() { add('Connection closed'); window.clearTimeout(timer); }; } else { alert("Your browser doesn't support WebSocket"); } </script> <form> <textarea name="b" style="width:100%;height:100%"/></textarea> </form> 

  4. Restart the daemon:
     # phpd restart 

  5. Open our HTML file in the browser (I checked only in Opera 12.13 and Google Chrome 24.0.1312.57).


After that, the JS-client starts interacting with the server and all their interactions will be displayed in the browser.

Note


The server has a timeout equal to two minutes (120 seconds). Accordingly, the client must periodically send "dummy" messages to the server so that the server does not consider it inactive and does not disable it. And don't forget to replace site.com with your host address.

PS The article was updated on 02/19/2014 and adapted to the current version of the framework (1.0-beta3).

Source: https://habr.com/ru/post/168059/


All Articles