使用PHP从Pusher通道获取信息

时间:2013-09-27 10:21:20

标签: php pusher

我对“Pusher”(websocket api)不熟悉,我很难理解如何在将信息发送到频道后从服务器获取信息。 例如,这是我的代码:

<?php
    include "pusher/Pusher.php";
?>
<script src="http://js.pusher.com/2.1/pusher.min.js"></script>
<script type="text/javascript">
    var pusher = new Pusher('c77c12b92e38f4156e9c');
    var channel = pusher.subscribe('test-channel');
    channel.bind('my-event', function(data) {
      alert('An event was triggered with message: ' + data.message);
    });
</script>
<?php
    $pusher = new Pusher($config["pusher_key"], $config["pusher_secret"], $config["pusher_id"]);
    $pusher->trigger(channel, 'my-event', array('message' => 'Test Message') );

现在,我的信息被发送到服务器,但我不知道如何获取它。

感谢。

2 个答案:

答案 0 :(得分:2)

您可以在此处找到一个非常简单示例的来源: https://github.com/leggetter/pusher-examples/tree/master/php/hello-world/src

这个例子在这里工作: http://www.leggetter.co.uk/pusher/pusher-examples/php/hello-world/src/

您看到的问题是您在浏览器中呈现页面之前在服务器上触发事件。因此,浏览器尚未与Pusher建立连接,也未进行订阅。

答案 1 :(得分:1)

您可以尝试这样的东西,对于我使用作曲家的php推送库

<div class="notification">
</div>

<script>
var pusher = new Pusher('APP_KEY');
var notificationsChannel = pusher.subscribe('notification');
notificationsChannel.bind('new_notification', function(notification){
    var message = notification.message;
    toastr.success(message);
});
var sendNotification = function(){
    var text = $('input.create-notification').val();
    $.post('./notification/index.php', {message: text}).success(function(){
        console.log('Notification sent!');
    });
};

$('button.submit-notification').on('click', sendNotification);

</script>

HTML

<input class="create-notification" placeholder="Send a notification :)"/>
<button class="submit-notification">Go!</button>

在这种情况下使用PHP

require(dirname(__FILE__).'/../vendor/autoload.php');
$app_id = 'APP_ID';
$app_key = 'APP_KEY';
$app_secret = 'APP_SECRET';
$pusher = new Pusher($app_key, $app_secret, $app_id,array( 'encrypted' => true ));
$data['message'] = $_POST['message'];
$pusher->trigger('notification', 'new_notification', $data);

如需更多关注this link

推荐的文件夹结构 -

enter image description here

您可以添加以下内容以获得更多用户体验 -

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="http://js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>