0

我对“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') );

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

谢谢。

4

2 回答 2

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 建立连接,也没有进行订阅。

于 2013-09-27T10:38:01.573 回答
1

你可以试试这样的东西,对于我使用作曲家的 php pusher 库

<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);

更多请点击此链接

推荐的文件夹结构 -

在此处输入图像描述

您可以添加以下内容以获得更多 UX kind'a 外观 -

<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>
于 2016-07-26T19:21:57.277 回答