从服务器推送更新

发布于 2024-11-27 23:15:53 字数 82 浏览 1 评论 0 原文

我想构建一个实时仪表板,一旦有任何更新,脚本就可以轮询并将更新推送到仪表板。任何人都可以告诉什么是最好的方法来做到这一点。 Node.js 有帮助吗?

I would like to build a realtime dashboard where as soon as there is any update, the script could poll and push the updates to the dashboard. Can anybody tell what would be the best way to do this. Will node.js help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独患者 2024-12-04 23:15:53

更新
截至 2013 年 8 月 10 日:node.js 缺乏库和支持的问题实际上已经基本消失,因为有了像mean.io 这样的库,您实际上可以在几小时内启动并运行一个库。

正如上面两个回复中所告诉的,阿努什的信息非常丰富,您有两种针对服务器端的解决方案。

  1. Node.js Based 'Event based' server
  2. PHP/ASP.net based polling/comet/forever script based server

据我所知和经验,Node.js 和 Socket.io 具有很大的优势,因为它们简单且具有开发实时 Web 应用程序的目的
,但是“Php 稳定强大”,所以这里是上述两个框架的一些优点和缺点。

PHP
优点

  1. 稳定性

  2. 功能

  3. 如果您熟悉 C++(如后端),则可以轻松编程

  4. 一个巨大的在线支持库 (php.net)

PHP 上用于 RealTime API 的机制有缺点缺点

  1. 通常,当使用长轮询方法时,您的服务器每秒必须处理来自同一用户的 n 个请求。这1个请求包含8KB的请求数据+要发送到服务器以获取信息的cookie。这会增加服务器开销,并且您可能还希望每次都对客户端进行授权(为了更好的安全性),因此 1 个授权函数也会被调用 n 次,这实际上会增加服务器负载。 n 越低,你就会失去史诗般的实时性。 n 越高,您将在 4 小时内向 21 个人创建一百万个请求。

  2. 使用 Comet 时,您必须保持请求打开一段时间,并持续轮询数据库或服务器 API 以了解仪表板中的更改。由于没有打开 APACHE / IIS 线程,这会阻塞整个脚本并大幅增加服务器负载。 (Comet 依赖于 Keep Alive 服务器),如果与功能强大的服务器一起使用,它是一种特殊的解决方案,因此根据您的服务器做出明智的选择。

  3. 当使用 AJAX 的永久打开请求时。您连续打开 1 个请求并使其永远保持打开状态以侦听服务器端推送,您再次使服务器超载,如情况 2 所示。我完全不推荐这个,我在 http://chats.ws/ 上写了一个这样的小程序,请随意查看源代码并在控制台 /firebug 中检查它。但是当客户端上有大约 8 个人时,服务器就会崩溃。

  4. Php 套接字(这是内置的 1 个 BSD 套接字解决方案)在 php 中),这里的问题是您最多将绑定到几百个用户。否则,这是最好的解决方案。因为这为您提供了 php 的“功能”和“稳定性”,并且易于使用 Web 套接字。对于客户端,您可以使用免费的分布式 XMLsocket API 。但是这种样式的套接字最好用 Java 或 C++ 编写.

如果您不需要非常出色的实时 api,PHP 是一个不错的选择,并且它是编写动态网页的最佳语言,但是当涉及编写更快的应用程序时,PHP 就会退步,因为它会阻塞服务器并消耗更多资源。

现在来第二个解决方案。

Node.js
Node 是一个基于事件的服务器软件,这意味着它仅在事件发生时才起作用,例如当 Apache 或 PHP 启动时,它们会告诉主机操作系统它们将处理特定端口(例如端口 80)上的请求,现在它们持续保留在内存中,并且即使不使用资源也会吃掉资源。就像 comet/Forever Open Connections 中一样,从数据库获取数据的内部轮询会保持打开的 APACHE 线程永远消耗您的资源,但在 Node 的情况下,应用程序会启动 node.js 开始运行,并告诉操作系统何时让它知道在特定端口上发出请求,然后当请求到来时,它会进入睡眠状态(即不执行任何操作并让操作系统来处理它)。node.js 完成请求并再次进入睡眠状态,这意味着它会在需要时工作并开启其他情况下,内存保持空闲并且资源如CPU使用率低。

Node.js 相当新,有时相当不稳定,但如果编写得好,它会惊人地提高应用程序的性能。它有很好的支持,您可能想访问 chat.stackoverflow.com 上的 javascript 聊天室,以获取以 socket.io 作为后端的 Node.js 的帮助。

socket.io 的作用是,它允许程序员只编写他/她的应用程序,而不是通信所需的基本内容,它会自动处理 Order

  1. Web Socket
  2. Flash Socket 中的传输方法。
  3. JsonP 轮询
  4. XHR 轮询

这样做可以确保您的程序在所有 Web 浏览器和 Node.js 作为服务器上以相同的速度和质量运行。

当你学习 Node.js 时,你就会明白编写在 php 上极其困难的东西是多么容易。例如,在 php 上,永远打开代码,以便在从数据库可用时向用户发送数据(现在说 mysql)

<?php 
   ob_implicit_flush(true);
   set_timeout(0);
   $T = 0; // for the first run send all the events
  while(true){
   $query = mysql_query("select * from database where TimeStamp > ".$T);
   if(mysql_num_rows(query)>0){ // That is omg we have an updated thing
   $T = microtime(true); // this gives the variable the value of current time stamp
      while ($row = mysql_fetch_assoc($query))
       {  $result = process($row)    // say u have to do some processing on the row
          echo json_encode($result); // this will send the JSON formation to your client       for faster processing  
      }
    }
  }
?>

现在,您还需要一些东西来管理数据库的输入等等,所以还有 1 个 .php 格式的文件来获取输入。

相反,用socket.io编写的node.js代码将看起来像

// Assume all functions are declared.

   var io = require("socket.io").listen(82);
   io.sockets.on('connection',function(client){
   client.on('authorise',function(info){
   var signin = Authorise(info); // say the info packet contains information about client user pwd and the Authorise function checks for the data to be true or false and then acts accordingly returns a bool status which is true  on success with autorisation_id(a member variablE)for the client and false on failure with the reason on failure in the reason member variable inside the signin object.


    socket.emit('authorised',signin); 

    });


    client.on('request',function(data){
      var result = process(data);
      client.emit('reply',result); // yes you can also send straight javascript objects
     });
    client.on('some_other_event', function(ev){ // SOmething happend such as some long task completed or some other client send a message that can be sent this way.
      client.emit('event',ev);
    });
   .
   . 
   // and so on
   });

On client side a

    <script src="server:82/socket.io/socket.io.js"></scirpt>
    <script>
    var connection = io.connect("server:82");
     connection.on('event',function(data){ 
       Process_Event(data); // some function which processes event data
      });
     connection.on('authorised',function(data){ 
       Auth(data); // Some function which tells client hey you are authroised or not and why not
      });
     connection.on('reply',function(data){ 
     parse_reply(data); // some function that tells the client what is the reply of the request by server and what it has to do 
     });
     function Authorise(){ // Lets assume its called by some html event
      username = document.getElementById('username').value;
      password = document.getElementById('password').value;
      socket.emit('authorise',{usr:username,pass:password}); // sends the request to server     
      }
      function Request(req) {} // this is a function which is called by some script gives it the request as the parameter when calling
      { 
         socket.emit('request',req); // sends request to server
      }
    </script>

如果你还没有注意到后者中没有for/while(true)循环,因此它不会以任何方式阻塞服务器,这是使用的基本优势node.js 与 socket.io 通过 php 轮询 、 Comet 或 BSD 套接字。

现在,好的选择是你的了!选择明智的 :) 因为您的应用程序取决于它,请随时在 chat.stackoverflow.com 或此处提出更多疑问 :)

Update
As of 8-10-2013 : The point of library and support lacking for node.js has mostly disappeared infact due to libs like mean.io you can actually get yourself one up and running in matter or hours.

Anush as told in the above two replies which were really informative you have 2 solutions for the server side.

  1. Node.js Based 'Event based' server
  2. PHP/ASP.net based polling/comet/forever script based server

to the best of my knowledge and experiences Node.js and Socket.io has a very big upperhand because of the simplicity and there purpose of development for realtime web - applications
, But then "Php is stable powerful" so here are a few of the benifits and drawbacks of both the above mentioned frameworks.

PHP:
Benifits:

  1. Stability

  2. Power

  3. Ease of programming if you are familier with C++ like backend

  4. A huge online library for support (php.net)

Mechanisms on PHP for RealTime API's with drawbacks DrawBacks

  1. Generally when using Long Polling method your server has to process n requests from same user per second. this 1 request contains 8KB of request data + cookies to be sent to the server for fetching information. Which increases server overhead , and you might also want to authorise the client everytime (for better security) hence 1 function of authorisation will be called n times aswell which actually increases server load. with lower n you lose your epic realtime. with higher n you create a million requests with 21 people in 4 hours.

  2. While using Comet you will have to keep requests open for sometime and continously poll the database or your server API for changes in your dashboard . Which is blocking the whole script and increases the server load rebellously because of the no of APACHE / IIS threads open. (Comet relies on Keep Alive Server), Its exceptional solution if used with a powerful server so depending on your server make a wise choice.

  3. When using a forever open request by AJAX . where you open 1 request continously and keep it open forever to listen for server side push you extremely overload the server again as in case 2 . I would totally not recommend this i wrote a applet like this on http://chats.ws/ feel free to see the source code and inspect it in console /firebug. but the server crashes when there are like 8 people on the client.

  4. Php Sockets (this is a 1 shot BSD Socket Solution in built in php), the problem here is you will be bound to a few hundred users at most. This is the best solution otherwise.as this gives you the "power" and "stability" of php with ease of use with web-sockets. For client you can use the free distributed XMLsocket API .But such styles sockets are better written on Java or C++ instead.

PHP is good choice in case you require not very awesome realtime api's and its the best language to write dynamic web-pages but when it comes to writing a bit faster applications PHP falls back as it blocks the server and eats up more resources.

Now coming the the second solution.

Node.js
Node is an event based server software meaning it acts only when an event is happening say for instance when Apache or PHP starts they come and tell the host OS that they will handle requests on a specific port say port 80 now they continuously stay in memory and eat resources even when not used. Like in comet/Forever Open Connections the internal poll to fetch data from database keeps an open APACHE thread forever eating up your resources, but in case of Node the application starts node.js comes in action and it tells the OS to let it known when a request is made on a specific port then it goes to sleep(ie does not does anything and leaves the OS to handle it) when a request comes node.js completes the request and again goes to sleep meaning it works when its required and on other cases the memory stays free and resources like CPU usage are low .

Node.js is fairly new and quite unstable sometimes but if written nicely it boosts the performance of your application amazingly. It has a good support and you might want to visit the javascript chatroom on chat.stackoverflow.com to get help among node.js with socket.io as backend.

What socket.io does is that it allows the programmer to write only his/her application and NOT the basic things required for communication it automatically handles the transportation methods in the Order

  1. Web Socket
  2. Flash Socket.
  3. JsonP Polling
  4. XHR POLLING

doing this it makes sure that your program runs with the same speed and quality on all the web-browsers and Node.js as the server.

When you learn node.js you will understand how easy it is to write things which were extremely hard on php. for instance say on php forever open the code to send user the data when availibe from database (say mysql for now)

<?php 
   ob_implicit_flush(true);
   set_timeout(0);
   $T = 0; // for the first run send all the events
  while(true){
   $query = mysql_query("select * from database where TimeStamp > ".$T);
   if(mysql_num_rows(query)>0){ // That is omg we have an updated thing
   $T = microtime(true); // this gives the variable the value of current time stamp
      while ($row = mysql_fetch_assoc($query))
       {  $result = process($row)    // say u have to do some processing on the row
          echo json_encode($result); // this will send the JSON formation to your client       for faster processing  
      }
    }
  }
?>

Now you will also need something to manage the input to database and so on so 1 more file in .php format to take input.

Instead of this the node.js code written with socket.io will look like

// Assume all functions are declared.

   var io = require("socket.io").listen(82);
   io.sockets.on('connection',function(client){
   client.on('authorise',function(info){
   var signin = Authorise(info); // say the info packet contains information about client user pwd and the Authorise function checks for the data to be true or false and then acts accordingly returns a bool status which is true  on success with autorisation_id(a member variablE)for the client and false on failure with the reason on failure in the reason member variable inside the signin object.


    socket.emit('authorised',signin); 

    });


    client.on('request',function(data){
      var result = process(data);
      client.emit('reply',result); // yes you can also send straight javascript objects
     });
    client.on('some_other_event', function(ev){ // SOmething happend such as some long task completed or some other client send a message that can be sent this way.
      client.emit('event',ev);
    });
   .
   . 
   // and so on
   });

On client side a

    <script src="server:82/socket.io/socket.io.js"></scirpt>
    <script>
    var connection = io.connect("server:82");
     connection.on('event',function(data){ 
       Process_Event(data); // some function which processes event data
      });
     connection.on('authorised',function(data){ 
       Auth(data); // Some function which tells client hey you are authroised or not and why not
      });
     connection.on('reply',function(data){ 
     parse_reply(data); // some function that tells the client what is the reply of the request by server and what it has to do 
     });
     function Authorise(){ // Lets assume its called by some html event
      username = document.getElementById('username').value;
      password = document.getElementById('password').value;
      socket.emit('authorise',{usr:username,pass:password}); // sends the request to server     
      }
      function Request(req) {} // this is a function which is called by some script gives it the request as the parameter when calling
      { 
         socket.emit('request',req); // sends request to server
      }
    </script>

If you have NOT noted already there is NO for/while(true) loop in the latter and hence it doesnt blocks server in any way this isthe basic upperhand of using node.js with socket.io over php Polling , Comet , or BSD Sockets.

Now well choice is yours! Choose wise :) as your application depends on it feel free to ask more doubts on chat.stackoverflow.com or on here :)

薔薇婲 2024-12-04 23:15:53

我认为 Node.js 会有很大帮助,而且速度会很快。我建议您查看 socket.io

I think node.js will help a lot and will be fast. I would advice you to have a look at socket.io.

淡忘如思 2024-12-04 23:15:53

我会看看 ajax,它是一个使用 javascript 和 javascript 的系统。 css 从后端(php、asp.net 等)检索信息,而不重新加载整个页面。

然后是反向 ajax,它基本上打开到服务器的连接,但服务器不会返回任何保持连接打开的内容。这使得客户端不必轮询服务器(反复询问服务器)信息,从而减少用户和服务器的带宽成本。客户端可以只打开一个连接,服务器可以在信息可用时发送信息(将推送信息复制到客户端,即使客户端启动了连接)。

另外,这里有一篇文章更深入地介绍了反向ajax以及不同的实现:http://gmapsdotnetcontrol.blogspot.com/2006/08/exploring-reverse-ajax-ajax.html (感谢 jacob)

node.js 是 JavaScript 的服务器端实现(据我所知)。这不是必需的,后端可以用 php、asp.net 或任何其他语言编写。尽管您应该阅读 Darkyen 的回答,但他提出了一些关于为什么节点的重要观点对于此类工作,.js 是比 php 更好的后端。不过,您需要的是一个使 ajax 变得简单的库。我使用 jquery,但有很多很棒的库可供选择,包括prototype、Mootools 和 YUI。

我希望这对你有帮助。

I'd look at ajax, it's a system that uses javascript & css to retrieve information from a back end (php, asp.net, etc) while not reloading the entire page.

Then there is reverse ajax, which basically opens a connection to the server, but the server won't return anything keeping the connection open. This keeps the client from having to poll the server (repeatably ask the server) for information which cuts down on bandwidth costs for both the user and server. The client can just open a connection, and the server can send information when it's available (replicates pushing information to the client, even though the client started the connection).

Also, here is an article going more indepth about reverse-ajax, and the different implementations: http://gmapsdotnetcontrol.blogspot.com/2006/08/exploring-reverse-ajax-ajax.html (thanks jacob)

node.js is a server side implementation of JavaScript (to my knowledge). This isn't needed, a back end can be written in php, asp.net, or really anything. Though you should read Darkyen's answer, he brings up some great points on why node.js is a better backend then say php for this type of work. What you will want though is a library to make ajax easy. I use jquery, but there are plenty of great libraries to choose from, including prototype, Mootools, and YUI.

I hope this helps you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文