node.js - 如何最好地使用socket.io和pub/sub创建与API调用的连接-Node.js

标签 node.js sockets real-time stockquotes

我已经创建了我的第一个Nodejs应用程序。我正在使用socket.io并表达。我尝试了本教程:https://socket.io/get-started/chat/,我发现发出是我可能不需要确定的内容。

我的应用程序显示股票行情自动收录器,我正在使用API​​,我的网址类似:https://quotes.example.com/v1/file.json/johndoe?&_token=tokenumber

所有打开http://example.com/live页面的用户,我想将此页面推送或发出股票行情自动收录器。我如何最好地做到这一点?我认为实时页面的想法必须是所有用户都可以订阅的 channel ,并且我正在向其中推送数据。

我以前从未从事实时应用程序的工作,欢迎提出所有建议。

已编辑

前端代码

<!doctype html>
<html>
  <head>
    <title>Live Stock Quotes App</title>
    <style>
      body { font: 26px Helvetica, Arial; font-weight:bold;}

      #livequotes { text-align: center;}
    </style>
  </head>
  <body>
    <p id="livequotes"></p>


    <script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>

<script>
  $(function () {
    var socket = io('/channel1');

     socket.on('live-quote', function(msg){
      $('#livequotes').text(msg);
    });
  });
</script>

  </body>
</html>

服务器端代码
var app = require('express')();
var http = require('http').Server(app);
var httpk = require('http');
var io = require('socket.io')(http);
var nsp = io.of('/channel1');

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

nsp.on('connection', function(socket){

  nsp.emit('live-quote', 'Welcome User!');
  //Make a http call

  function test()
  {
    httpk.get("url-to-api", function(res) {
        var body = ''; // Will contain the final response

        res.on('data', function(data){
            body += data;
        });

        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.bid_price);
            return parsed.johndoe.bid_price;
        });
    });
  }

  setInterval(test,500);

  socket.on('disconnect', function(){
    console.log('1 user disconnected');
  });

});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

上面的代码我已经按照您的建议放置了。现在,我想添加以下内容:
setInterval(test,500);

function test (){
    http.get("url-for-api", function(res) {
        var body = ''; // Will contain the final response

            res.on('data', function(data){
            body += data;
        });

        // After the response is completed, parse it and log it to the console
        res.on('end', function() {
            var parsed = JSON.parse(body);
            console.log(parsed.johndoe.bid_price);
            data = parsed.johndoe.ask_price;

        });
    })
    // If any error has occured, log error to console
        .on('error', function(e) {
            console.log("Got error: " + e.message);
        });

}

最佳答案

您要问的是什么还不是很清楚,但是我会对此一视同仁。

如果您希望能够使用socket.io将新的股票更新“推送”到客户端,则通常的做法是客户端将socket.io连接到服务器,然后服务器可以发布更新到通过在服务器上执行io.emit(msg, data),所有连接的客户端。这会将消息和数据发送到所有连接的客户端。

如果要将这些更新发送到网页,则将Javascript放入该网页中,以使socket.io连接到服务器,然后在该套接字上监听来自服务器的适当消息。当它从服务器接收消息时,它可以按照您认为合适的任何方式将它们插入页面。

来自socket.io doc pages的此客户端代码将是客户端的典型代码:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('udpate', function (data) {
    console.log(data);
    // do something with the data here (like insert it into the web page)
  });
</script>

如果您必须告诉服务器您感兴趣的库存更新,以便仅将这些更新发送到客户端页面,那么您将需要在客户端和服务器上都做更多的工作,以使服务器能够跟踪哪个连接是对哪些更新感兴趣,仅发送到正确的连接。您可以使用socket.io房间来帮助管理。客户连接请求加入给定存量的房间,然后仅将特定股票的存货更新发送给该相应房间中的客户。

关于node.js - 如何最好地使用socket.io和pub/sub创建与API调用的连接-Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44488279/

相关文章:

node.js - knexjs postgresql 迁移运行不正常

Java 空套接字

C Accept Client Socket "Invalid Argument"添加信号线程时出错

c - 不支持获取 ai_socktype

iphone - iOS 实时音频 I/O

javascript - Node.js 上的 While 循环具有异步数据

node.js - SocketIO 在自签名证书上抛出 net::ERR_CERT_AUTHORITY_INVALID

node.js - 在 ubuntu 上安装 socket.io

javascript - "TypeError: Cannot read property ' s ' of undefined"。 agenda.js 中的 this 是什么意思?

ios - 实时视频流传输至 iPad 应用程序