【问题标题】:How can a server (node) let a client know that there are updates to fetch?服务器(节点)如何让客户端知道有更新要获取?
【发布时间】:2015-08-27 16:08:39
【问题描述】:

我目前正在学习如何使用 nodeJS 服务器。 我使用 ReactJS 进行客户端渲染。

我想知道的一件事是,当我有新数据需要客户端获取时,我如何让客户端知道?最好的方法是什么?

例如用于某种聊天或类似的事情。

【问题讨论】:

  • 它不能,除非服务器设置为推送更新而不是客户端获取它们。 (又名网络套接字)

标签: node.js server


【解决方案1】:

HTTP 是一种请求-响应协议,只能在客户端启动。因此,您需要研究诸如彗星或长轮询之类的解决方法,或者研究诸如 websockets 之类的替代技术,这些技术允许在浏览器中进行双向通信。

http://www.pubnub.com/blog/http-long-polling/

http://socket.io/

【讨论】:

    【解决方案2】:

    看看http://socket.io/

    我只能举个例子。

    server.js

    io.sockets.on('connection', function(socket) {
      console.log(__dirname);
      // watching file
      fs.watchFile(__dirname + '/example.txt', function(curr, prev) {
        // on file change we can read the new file
        fs.readFile(__dirname + '/example.txt', function(err, data) {
          if (err) throw err;
          // parsing the new txt and make it json just my preference
          var json = parser.toJson(data);
          // send the new data to the client
          socket.volatile.emit('notification', json);
        });
      });
    

    前端.html

    <script src="socket.io/socket.io.js"></script>
        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        <script>
        // creating a new websocket
        var socket = io.connect('http://localhost:8000');
        // on every message recived we print the new datas inside div
        socket.on('notification', function (data) {
            // json string into a valid javascript object
            var _data = JSON.parse(data);
    
            $('#container').html(_data.test.sample);
            $('time').html('Last Update:' + new Date());
        });
        </script>
    

    所以基本上当我的数据文件在服务器上更新时,我使用 websocket 来保持服务器和客户端之间的连接处于活动状态。每次更改时,它都会使用文件中的新数据更新客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2016-06-20
      • 2021-07-22
      • 2012-02-06
      相关资源
      最近更新 更多