reich / longpolling
编写长轮询应用程序的直观且简洁的方法
v1.0
2018-03-25 22:59 UTC
Requires
- php: >=5.6.0
This package is not auto-updated.
Last update: 2024-09-24 17:11:03 UTC
README
长轮询
编写长轮询应用程序的直观且简洁的方法
安装
对于javascript模块:只需将src/js/LongPolling.js导入到您的项目中,并在html中嵌入即可
对于PHP文件,您可以使用composer
composer require reich/longpolling
用法
在服务器端,您需要使用以下代码片段监听更改
\Reich\PHP\LongPolling::check(1000, function() { // we are inside a continuing loop, // return some data to the client. // Only if the data has been changed / modified // the client will recieve the changes. });
在这里,我们每秒检查一次数据更改,如果返回的值没有变化,则不会发生任何操作。如果数据确实已更改,客户端将接收到新数据。
在客户端使用javascript时,我们需要设置一个监听器以接收更改的数据
<div id="recipes"> <!-- Loading the modified recipes from the server --> </div>
(function(LongPolling) { LongPolling.get('server.php').subscribe(function(recipes) { var recipes = JSON.parse(recipes); var div = document.getElementById('recipes'); var output = ''; for (var recipe in recipes) { output += '<li>Recipe: '+recipe+', Price: '+recipes[recipe]+'</li>'; } div.innerHTML = output; }); })(LongPolling);
注意事项
许多大型平台,如facebook、twitter以及许多其他富互联网应用程序都使用了这种技术。
这是一个非常简单但非常强大的概念。现在,我们的用户无需刷新浏览器即可看到更改:)