2014-03-14 47 views

回答

2

您對使用React EventLoop的假設是正確的。您可以使用定期計時器來觸發發送消息。既然你提到了Ratchet併發布了+訂閱,我會假設你正在使用WAMP而不是WebSockets。以下是一些示例代碼:

<?php 
use Ratchet\ConnectionInterface; 

class MyApp implements \Ratchet\Wamp\WampServerInterface { 
    protected $subscribedTopics = array(); 

    public function onSubscribe(ConnectionInterface $conn, $topic) { 
     // When a visitor subscribes to a topic link the Topic object in a lookup array 
     if (!array_key_exists($topic->getId(), $this->subscribedTopics)) { 
      $this->subscribedTopics[$topic->getId()] = $topic; 
     } 
    } 
    public function onUnSubscribe(ConnectionInterface $conn, $topic) {} 
    public function onOpen(ConnectionInterface $conn) {} 
    public function onClose(ConnectionInterface $conn) {} 
    public function onCall(ConnectionInterface $conn, $id, $topic, array $params) {} 
    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible) {} 
    public function onError(ConnectionInterface $conn, \Exception $e) {} 

    public function doMyBroadcast($topic, $msg) { 
     if (array_key_exists($topic, $this->subscribedTopics)) { 
      $this->subscribedTopics[$topic]->broadcast($msg); 
     } 
    } 
} 

    $myApp = new MyApp; 
    $loop = \React\EventLoop\Factory::create(); 
    $app = new \Ratchet\App('localhost', 8080, '127.0.0.1', $loop); 
    $app->route('/my-endpoint', $myApp); 

    // Every 5 seconds send "Hello subscribers!" to everyone subscribed to the "theTopicToSendTo" topic/channel 
    $loop->addPeriodicTimer(5, function($timer) use ($myApp) { 
     $myApp->doMyBroadcast('theTopicToSendTo', 'Hello subscribers!'); 
    }); 

    $app->run(); 
+0

如果客戶端發佈到某個主題如何將數據導入到onPublish()方法中?我使用的是authobhan js – ravisoni

+0

conn.publish('kittensCategory',['Hello,world!']);我怎麼能在服務器上的onPublish方法中獲得hello world – ravisoni