php - 如何从服务器接收更新而不每隔 n 秒请求一次

标签 php mysql node.js angularjs cordova

我正在构建一个移动应用程序,每当服务器有新数据可用时,它就会从服务器接收数据。我正在为我的移动应用程序使用 cordova 和 ionic 框架,并为移动应用程序获取数据的 API 和服务器使用 PHP/MySQL/Apache。

有什么方法可以让我从服务器检索数据(JSON 格式),而无需使用 http.get 每 n 秒不断请求数据?在我的移动应用程序中?因为我只需要在有新数据时获取,而不是一直有新数据,但有时在高峰时每秒都有新数据。 Apache/PHP 可以处理这个问题还是我需要切换到 Nodejs 之类的?提前致谢。

顺便说一句,我希望我的移动应用程序在一秒钟内收到数据。

我的问题与此Receive update from server with mobile framework非常相似和 https://softwareengineering.stackexchange.com/questions/225589/how-to-refresh-keep-up-to-date-content-in-the-browser-without-overloading-the-se但我现在还悬着。

最佳答案

Node.js 和 Socket.io 使类似的事情变得几乎微不足道,但是您几乎可以使用任何 Web 后端来完成此操作。有几种选择可以做到这一点,但只要有可能,我都会倾向于使用 websocket。我从来没有用过,但是Ratchet似乎可以满足您对 PHP 的需求。看看他们的Hello World tutorial了解如何设置。

更新

由于您使用的是 Cordova,因此 Websocket 很有意义。以下是使用 socket.io 在 Node.js 中实现的示例。

var app = require('http').createServer(handler);
var io = require('socket.io')(app);

app.listen(80);

function handler (req, res) {
  // We aren't serving any http requests outside of socket.io. 
  // Return a 404 error for all other requests.
  res.status(404).send('Not found');
}

io.on('connection', function (socket) {
  //  This is either a new client connection, or a client reconnecting. 
  //  You can use cookies to establish identity and handle reconnects 
  //  differently if necessary.

  socket.on('new-content', function(content) {
    //  persist the file in the database if necessary and resend it to all 
    //  connected clients
    socket.broadcast.emit('new-content', content);
  });
});

这里我们只是创建一个简单的中继服务器。您可以发送一个"file",在本例中只是一串内容,它将发送给所有其他连接的用户。在这种情况下,您不必继续查询数据库来查找新内容,您可以根据来自客户端的内容触发它。如果您希望离线用户能够在上线时接收该内容,则需要某种持久性和机制来跟踪和处理该内容。

客户端脚本也非常简单。

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://myserver.com');
  socket.on('new-file function (content) {
    // A new file was sent from the server, do something with the content here.
  });

  function sendFile(content) {
    socket.emit('new-file', content);  
  }
</script>

关于php - 如何从服务器接收更新而不每隔 n 秒请求一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26282262/

相关文章:

php - 在 Woocommerce 订单销售报告中包含自定义订单状态

mysql - 根据个人搜索条件获取通过特定摄像头的汽车

php - 变量连接的 mysql 查询字符串在 phpMyAdmin 中运行良好,但在脚本中运行 PHP 则不行

javascript - 将回调转换为 Promise 语法

javascript - Node.js 支持 =>(箭头函数)

php - session 重新生成

php - Http 服务器使用 C++ 将数据发布到 php-cgi

php - 查找交易文件中100笔交易中连续出现5个以上序号的事件

MySQL DISTINCT 在一个列上且与另一列不匹配

mysql - NodeJs & MySql : results. 当表 id 是 UUID 时 insertId 总是 0