【发布时间】:2015-10-10 21:22:01
【问题描述】:
我已经编写了我的应用程序,现在我已经激活了 New Relic,它每 30 分钟对我的应用程序执行一次 ping 操作,以保持我的服务器处于活动状态 (heroku)。否则,在服务器将只是空闲然后在第一个请求上花费大量时间重新启动之前。
我正在运行一个 socket.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);
【问题讨论】:
标签: javascript mysql node.js sockets