无法将获取的数据发送到我的socket.io流?

时间:2015-05-05 11:55:42

标签: javascript mysql node.js websocket socket.io

我试图从单个mysql查询切换到mysql-pool连接,因此用户可以共享一个mysql连接,但我根本不熟悉这个(对于nodejs / socket也是新手) .IO)。

以下代码是我到目前为止每秒向数组中的套接字发送数据所做的:

var 
port                = process.env.OPENSHIFT_NODEJS_PORT || 8000,
ip                  = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1',
app                 = require('http').createServer(handler),
fs                  = require('fs'),
request             = require('request'),
mysql               = require('mysql'),
moment              = require('moment'),
tz                  = require('moment-timezone'),
pool                = mysql.createPool({
connectionLimit:    100,
host:               'xxx',
user:               'xxx',
password:           'xxx',
database:           'xxx',
debug:              false,
port:               3306}),
socketArray         = [],
POLLING_INTERVAL    = 1000,
pollingTimer;
moment.tz.setDefault("Europe/Berlin");

var io = require('socket.io').listen(app);
io.set('origins', '*:*');

function time()
{
output = new Date();
output = moment().format('(H:mm:ss.SS) ');
return output;
}

function handler(req,res) 
    {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.statusCode = 200;
    res.connection.setTimeout(0);
    res.end();
}
app.listen(port,ip);

function pollingLoop () {
    if (socketArray.length === 0) {
        // no connections, wait and try again
        setTimeout(pollingLoop, POLLING_INTERVAL);
        return; // continue without sending mysql query
    }
    pool.getConnection(function(err,connection){ 
    if (err) { console.log({"code" : 100, "status" : "connection-db error"}); return; }   
    console.log('connected as id ' + connection.threadId);
    console.log('socketArray length: ' + socketArray.length);

    var selection = 
        "SELECT\
        a.`id`,a.`product_id` AS pid,a.`random` AS nr,a.`price`,a.`price_end` AS pe,\
        TIMESTAMPDIFF(SECOND,NOW(),a.`datetime`) AS duration,\
        ABS(TIMESTAMPDIFF(SECOND,NOW(),b.`date`)) AS hb\
        FROM `auctions` AS a\
        LEFT JOIN `auctions_bids` AS b ON b.`auction_id` = a.`id`\
        WHERE TIMESTAMPDIFF(SECOND,NOW(),a.`datetime`) > '-1'\
        GROUP BY a.`id`\
        ORDER BY `duration` DESC,`id` DESC LIMIT 15";   
    var streamArray = [], lg = '';                      

    var query = connection.query(selection, function(err, results, rows){
    lg += ('id: '+results[0].id+' ('+results[0].duration+') ');         

    if 
    (
    ((results[0].duration < 2 || results[0].duration <= results[0].nr) && (results[0].price <= results[0].pe)) 
    ||
    ((results[0].duration < 2 || results[0].duration <= results[0].nr) && (results[0].hb > 0 && results[0].hb < 30))
    )   
    {
    min = 3;
    max = 5;
    rand = Math.floor(Math.random()*(max-min+1)+min);
    price = results[0].price+0.01;
    price = price.toFixed(2);

    pool.query('UPDATE `auctions` SET `random` = ?,`price` = ?, `datetime` = DATE_ADD(`datetime`,INTERVAL(17-TIMESTAMPDIFF(SECOND,NOW(),`datetime`))SECOND) WHERE `id` = ?',[rand, price, results[0].id]);  
    console.log(time()+'UPDATED id '+results[0].id+': random ('+rand+') price ('+price+'€)');   
    }       
    streamArray.push(results[0]);        

    updateSockets({ streamArray: streamArray });    
    console.log("auctions pushed: " + streamArray); 
    connection.release();
    setTimeout(pollingLoop, POLLING_INTERVAL);  
    });
    console.log(time()+lg+' C: '+socketArray.length);
}); 
}
pollingLoop();

io.sockets.on('connection', function(socket) {  
    socket.on('disconnect', function() {
    clearTimeout(pollingTimer);
    var socketIndex = socketArray.indexOf(socket);
    console.log(time()+'SOCKET-ID = %s DISCONNECTED', socketIndex);
    if (~socketIndex) { socketArray.splice(socketIndex, 1); }
    });  
    console.log(time()+'NEW SOCKET CONNECTED!');
    socketArray.push(socket);
}); 

var updateSockets = function(data) {
    socketArray.forEach(function(tmpSocket) { tmpSocket.volatile.emit('stream', data); });
};

console.log(time()+'server.js executed\n');

但是这并没有向WebSocket发送任何数据。这种方法(代码结构)是否正确?以前我使用query.on('results')来获取这样的数据:

var selection = "SELECT * FROM auctions";            
var query = mysql.query(selection), auctions = []; 
query.on('result', function(auction) {
console.log('id: '+auction.id+' ('+auction.duration+') ');
});

这可以很好地显示auction.row的数据,但是如何在我的mysql池连接中执行此操作?

也过了几秒钟我收到release()甚至没有定义的错误,但它在mysql-module文档中列出了...所以我想我的整个逻辑过程在某种程度上是错误的。

  1. 我应该使用connection.end()和.release()吗?因为 连接永远不会结束。
  2. 我是否仍应使用另一个StackOverflow问题中的setInterval(function () { mysql.query('SELECT
    1'); }, 5000);
    作为答案 连接在这里活着? (nodejs mysql Error: Connection lost The server closed the connection
  3. (对我的一些问题感谢任何提示或答案!更好的答案比没有答案更好,因为我经历过这个话题没有得到很多回答。)

    修改 更新了我的整个代码(见上文)。输出现在看起来像这样:http://s21.postimg.org/avsxa87rb/output.jpg

    所以流获取数据,但是在console.log中什么都没有,并且出现了这个javascript错误?

1 个答案:

答案 0 :(得分:0)

您应该创建一个池,并在该池上使用getConnection。然后,当您完成连接后,将其释放。此外,您不需要停止pollingLoop或为每个连接启动它,一个循环就足够了。

我没有理解带有条件的if语句,所以我省略了它。它可能需要去其他地方。

var socketArr = [];

function handler(req, res) {
    res.statusCode = 200;
    res.connection.setTimeout(0);
    res.end();
}
app.listen(port, ip);
var pool = mysql.createPool({
    host     : 'example.org',
    user     : 'bob',
    password : 'secret'
});

function pollingLoop () {
    if (socketArr.length === 0) {
        // no connections, wait and try again
        setTimeout(pollingLoop, 1000);
        return; // continue without sending mysql query
    }
    pool.getConnection(function (err, connection) {
        if (err) {
            console.log({
                "code": 100,
                "status": "Error in connection database"
            });
            return;
        }
        console.log('connected as id ' + connection.threadId);
        var selection = "SELECT * FROM auctions";
        var streamArray = [],
            lg = '';
        var query = connection.query(selection, function (err, results, fields, rows) {
            lg += ('id: ' + results[0].id + ' (' + results[0].duration + ') ');
            /*if (conditions) {
                var query_update = connection.query('UPDATE `auctions` SET `price` = ? WHERE `id` = ?', [price, auction.id]);
                console.log(time() + 'UPDATED id ' + auction.id + ': price (' + price + '€)');
            }*/
            streamArray.push(results);
            updateSockets({
                streamArray: streamArray
            });
            console.log("auctions pushed: " + streamArray);
            connection.release();
            setTimeout(pollingLoop, 1000);
        });
        console.log(time() + lg + ' C: ' + socketArr.length);
    });
}
// start loop
pollingLoop();

io.sockets.on('connection', function (socket) {
    socket.on('disconnect', function () {
        var socketIndex = socketArr.indexOf(socket);
        console.log(time() + 'SOCKET-ID = %s DISCONNECTED', socketIndex);
        if (~socketIndex) {
            socketArr.splice(socketIndex, 1);
        }
    });
    console.log(time() + 'NEW SOCKET CONNECTED!');
    socketArr.push(socket);
});
var updateSockets = function (data) {
    socketArr.forEach(function (tmpSocket) {
        tmpSocket.volatile.emit('stream', data);
    });
};