推送通知是如何工作的

How do push notifications work?

本文关键字:工作 何工作 通知      更新时间:2024-01-01

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

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

从文献中我很难理解sending.phpreceiving.php页面是如何通过程序设置的。我认为sending.php页面只涉及到某个页面的$_POST['message'],但从那以后我真的迷失了方向。

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

工作

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

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

入门

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

HTML5岩石

Nettuts+

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

对于支持Websockets 的浏览器

回退

您可以使用Modernizr来检测客户端的浏览器是否支持websocket&作为后备方案,您可以使用flash而不是Websockets。

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

任何带有Flash的浏览器都可以使用web套接字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

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

给我印象最深的是,你只需要写很少的代码就可以实现这一点。请参见下文。我的服务器端是用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>