推送通知如何工作?

我正在尝试在基于PHP的网站上实现推送通知。目标是制作类似于Stackoverflow和其他网站的东西,当用户收到消息时,实时通知用户。

我使用mysql作为我的数据库,Apache作为我的服务器,并且正在考虑使用Amazon-SNS作为这些通知的框架,因为这似乎是该服务的目的。

我从文献中很难理解和页面是如何以编程方式设置的。我假设该页面只涉及某个页面,但从那里我真的迷路了。sending.phpreceiving.phpsending.php$_POST['message']

如果有什么东西可以帮助我理解推送通知的页面会是什么样子,我将不胜感激。receiving.php


答案 1

加工

HTML5rocks在这里提供了一个很好的解释,关于websockets是如何工作的。

好吧,您可以为支持它的浏览器使用Websockets(因为所有现代浏览器都提供了良好的支持)

开始

您可以从以下几个资源开始:

HTML5rocks

网易娱乐+

Nettuts+为开始使用websockets提供了一个很好的教程。

对于支持 Websockets 的浏览器

后备

您可以使用Modernizr来检测客户端的浏览器是否支持websockets,作为回退,您可以使用flash而不是Websockets。

对于这些项目,当在没有WebSockets或禁用WebSockets的浏览器上运行时,将使用web-socket-js。它的效率将低于本机,但延迟仍比长轮询低得多。

任何带有Flash的浏览器都可以使用Web-socket-js shim/polyfill来支持WebSocket。

参考:

WebSockets 的替代方案

https://softwareengineering.stackexchange.com/questions/33713/is-there-an-alternative-to-html-web-sockets-now-that-firefox-4-has-disabled-the


答案 2

我只是想分享我使用的实际实现。我决定使用一个伟大的SAAS,Pusher,因为在实现Push通知时存在许多具有挑战性的问题,正如我在阅读@Virendra优秀答案中的链接时意识到的那样,Pusher为您解决了问题。

我印象最深刻的是,你必须编写很少的代码来使它工作。见下文。我的服务器端是PHP的(Pusher有很多语言的库)。

require('/application/thirdParty/pusher-html5-realtime-push-notifications/lib/squeeks-Pusher-PHP/lib/Pusher.php');
require('/application/thirdParty/pusher-html5-realtime-push-notifications/config.php');
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);

foreach($recipients as $row){                   
  $channel='my-channel'.$row->recipient_id;
  $pusher->trigger($channel, 'notifications', 
    array('message' => $row->message,
          'notification_id' => $row->notification_id) 
  );
}

这是HTML / JS(不要不知所措,大部分代码只是为了填充小圆圈和列表,如Stackoverflow和其他人这样做):

<script src="/application/thirdParty/pusher.min.js"></script>
<script>     
var myID=179; // would receive notification if myID matches $row->recipient_id above;
var myChannel = pusher.subscribe('my-channel'+myID);
myChannel.bind('notifications',
  function(data) {
        var message=String(data.message),
            url='/notifications/'+data.notification_id, 
            icon='<i class=\'icon-heart\'></i>',
            urlText=icon+message;

        var notificationRow='<li><a href='+url+'>'+urlText+'</a></li>';
         $('#notificationsDropdownList').prepend(notificationRow);   

        if(notificationCircleCount==0){
             notificationCircleCount++;
              $notificationCircle.show();
               $notificationCircleCount.html(notificationCircleCount);
        }
        else{
             notificationCircleCount++;
             $notificationCircleCount.html(notificationCircleCount);
        }
        console.log('Pusher happened'+data.message);                  
  } //function
); //myChannel
</script>