【问题标题】:How do I use a Node.js server to continuously push updates of an array to localhost如何使用 Node.js 服务器将数组的更新持续推送到 localhost
【发布时间】:2019-09-08 02:46:07
【问题描述】:

我创建了一个空数组,将名字键的值从一个单独的对象中放入其中,通过在 Node.js 中创建一个服务器将其发送到 localhost,然后循环返回以从另一个对象中获取新信息以推送到数组。但是当我在第二个循环中循环到服务器上的托管点时,我收到一条错误消息“抛出错误,地址已在 127.0.0.1:3000 使用

我不知道尝试将连续信息传递到正在运行的服务器的替代方法

var p = 0, repeat = 4
var indices = []

function f() {

//example of array information which is fed into the loop
var mc = [{ name: "Henry", output: -30 }, { name: "Kevin", output: -15 }, { name: "Jeremy", output: -40 }, {name: "Steven", output: 43}]


p++
if (p < repeat) {
setTimeout(f, 100)
}

var open = mc[0].name
indices.push(open)

//this is where the error occurs on the second loop, as the server is already running from the first loop and it can't access the address in use already
var toserver = JSON.stringify(indices)
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer(function (req, res) {
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'text/plain');
                        res.end(toserver);
                    });

                    server.listen(port, hostname, function () {
                        console.log('Server running at http://' + hostname + ':' + port + '/');
                    });

}
f()

我收到“抛出错误,地址已在 127.0.0.1:3000 使用”。我希望有人能告诉我如何不断更新这个服务器。阵列中的信息不断更新,可以在 console.log 上看到。但这是对服务器的更新,所以我可以在浏览器上查看它,这是问题所在。感谢您的关心。

【问题讨论】:

  • address already in use at 127.0.0.1:3000 所以,3000 端口上正在监听其他东西
  • so I can view it on the browser ... 调查服务器端事件或 websocket,或者只是让浏览器端定期“轮询”服务器

标签: javascript server push


【解决方案1】:

对于您尝试创建新服务器的每个周期,因此在第二次运行时它会失败并抛出错误,因为您已经在监听了。

只启动一次服务器,并按照 Jaromanda 的建议使用 websockets 或其他技术。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多