2014-10-01 79 views
3

我试图建立一个通知消息系统。我使用SimpleWsServer.php服务器示例。当服务器上的任务完成时,我想将通知推送给用户的浏览器。这需要使用PHP完成,我无法找到一个教程,这显示。所有的教程似乎都显示了在PHP服务器作为管理器运行时发送和接收的tavendo/AutobahnJS脚本。发送消息使用PHP与Voryx高速公路WAMP消息系统

是否可以使用PHP脚本向订阅者发送消息?

+0

不知道你要拉什么,但看起来Ajax是这里的路? – Naruto 2014-10-01 07:27:40

+0

@Naruto ajax不是实时的 – astroanu 2014-10-02 05:27:31

回答

7

Astro,

这实际上非常简单,可以通过几种不同的方式完成。我们设计了Thruway客户端来模仿AutobahnJS客户端,所以大多数简单的例子都会直接翻译。

我假设你想从一个网站发布(不是长时间运行的PHP脚本)。

在你的PHP的网站,你会想要做这样的事情:

$connection = new \Thruway\Connection(
    [ 
     "realm" => 'com.example.astro', 
     "url"  => 'ws://demo.thruway.ws:9090', //You can use this demo server or replace it with your router's IP 
    ] 
); 

$connection->on('open', function (\Thruway\ClientSession $session) use ($connection) { 

    //publish an event 
    $session->publish('com.example.hello', ['Hello, world from PHP!!!'], [], ["acknowledge" => true])->then(
     function() use ($connection) { 
      $connection->close(); //You must close the connection or this will hang 
      echo "Publish Acknowledged!\n"; 
     }, 
     function ($error) { 
      // publish failed 
      echo "Publish Error {$error}\n"; 
     } 
    ); 
    }); 

$connection->open(); 

和JavaScript客户端(使用AutobahnJS)看起来就像这样:

var connection = new autobahn.Connection({ 
    url: 'ws://demo.thruway.ws:9090', //You can use this demo server or replace it with your router's IP 
    realm: 'com.example.astro' 
}); 

connection.onopen = function (session) { 

    //subscribe to a topic 
    function onevent(args) { 
     console.log("Someone published this to 'com.example.hello': ", args);  
    } 

    session.subscribe('com.example.hello', onevent).then(
     function (subscription) { 
      console.log("subscription info", subscription); 
     }, 
     function (error) { 
      console.log("subscription error", error); 
     } 
    ); 
}; 

connection.open(); 

我也为javascript端创建了plunker,为PHP端创建了runnable

+1

哦,我的天哪$ connection-> close();为什么我没有得到那个。谢谢你..我喜欢你们如何模仿高速公路。再次感谢 ! – astroanu 2014-10-02 05:22:56