未知node.js和websockets服务器停止.谁修改了我的代码

Unknow node.js and websockets server stopping. Who revises my code?

本文关键字:修改 我的 代码 js node websockets 服务器 未知      更新时间:2023-09-26

我已经写了我的应用程序,现在我已经激活了New Relic,它每30分钟ping我的应用程序,以保持我的服务器存活(heroku)。否则之前服务器只是空转,然后在第一个请求上花费大量时间重新启动。

我正在运行套接字。IO服务器和我现在面临的问题是,经过大量的时间,服务器运行,它被困在回答名称空间。应用程序没有给出任何致命错误,它继续运行,只是停止回答。它保持正常工作(仍然检测和记录新连接的客户端),但只是不发送消息。

日志没有异常

你能帮我检查一下我的代码是否做错了什么,我不应该做的,可能会产生问题?(例如,监听器太多等)

我对我的代码做了一个小总结,所以可能会有一些愚蠢的语法错误,但流程应该是这样的。所有内容重复4,因为我有4个名称空间和4个不同的查询。

var app = require('express')();
var http = require('http').Server(app);
var cors = require('cors');
var io = require('socket.io')(http);
var PORT = process.env.PORT || 8080;
var sensorSocket = io.of('/namespace1'); //This gives back all the sensor at once with just now values.
var oldata = [];
var intervalRefresh=300;
app.use(cors());
var mysql = require('mysql');
var connectionsArray = [];
var connection = mysql.createConnection({
    host: 'xxx',
    user: 'xxx',
    password: 'xxx',
    database: 'xxx',
    port: xx,
    dateStrings: 'date'
})
//websockets creation/connection
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/client.html');
});
http.listen(PORT, function () {
    console.log(''n'n'n'n listening on port: %s', PORT);
});
io.of('/namespace1').on('connection', function (socket) {
    newconnectionSensors = 1;
    console.log("Client id: %s connected on /sensors", socket.id);
    console.log(io.of('/sensors').sockets.length);
    socket.on('disconnect', function () {
        console.log("Just left the ship grrarr : %s", socket.id);
    });
});
io.of('/namespace2').on('connection', function (socket) {
    [..Similar to the previous one..]
});

io.of('/namespace3').on('connection', function (socket) {
    [..Similar to the previous one..]
});

io.of('/namespace4').on('connection', function (socket) {
    [..Similar to the previous one..]
});
//Above here I do the same request every 300ms to the db and if there is any change, sends it into the client.
var CheckDB = setInterval(function (sensorSocket) {
    if (io.of('/namespace1').sockets.length > 0) {
        var query = connection.query('Query...'),
        data = []; // this array will contain the result of our db query
        query
            .on('error', function (err) {
                // Handle error, and 'end' event will be emitted after this as well
                console.log(err);
            })
            .on('result', function (result) {
                data.push(result);
            })
            .on('end', function () {
                if ((JSON.stringify(oldata) != JSON.stringify(data)) || newconnection == 1) { //if new data is different than the old data, update the clients
                    io.of('/namespace1').emit('message', dataSensors, io.of('/namespace1').sockets.id);
                    newconnection = 0;
                    oldata = data.slice(0); //copy of data to oldata
                }
            });
    }
}, intervalRefresh);
var CheckDB2 = setInterval(function (sensorSocket) {
        [..Similar to the previous one..]
}, intervalRefresh);
var CheckDB3 = setInterval(function (sensorSocket) {
        [..Similar to the previous one..]
}, intervalRefresh);
var CheckDB4 = setInterval(function (sensorSocket) {
        [..Similar to the previous one..]
}, intervalRefresh);

找到错误。

真正的错误是我没有真正清楚NodeJS的非阻塞概念,所以在代码中我没有等待MySQL服务器的答案,而是我只是向服务器抛出查询,所以结果将在几个小时后到达。

我通过逃跑来修复。基本上,我添加了一个var (queryexecution)来检查查询是否已经完成执行。

var CheckDB = setInterval(function (sensorSocket) {
    if (io.of('/namespace1').sockets.length > 0 && queryexecuting==0) { //If there are connected clients and there is no query executing.
        queryexecuting=1; //Means the query is working
        var query = connection.query('Query...'),
        data = [];
        query
            .on('error', function (err) {
                console.log(err);
            })
            .on('result', function (result) {
                data.push(result);
            })
            .on('end', function () {
                if ((JSON.stringify(oldata) != JSON.stringify(data)) || newconnection == 1) { 
                    io.of('/namespace1').emit('message', dataSensors, io.of('/namespace1').sockets.id);
                    newconnection = 0;
                    oldata = data.slice(0);
                }
                queryexecuting=0; //Means the query has been finished
            });
    }
}, intervalRefresh);