pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

無法將獲取的數(shù)據(jù)發(fā)送到我的 socket.io 流?

Can#39;t send fetched data to my socket.io stream?(無法將獲取的數(shù)據(jù)發(fā)送到我的 socket.io 流?)
本文介紹了無法將獲取的數(shù)據(jù)發(fā)送到我的 socket.io 流?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

限時送ChatGPT賬號..

我正在嘗試從單個 mysql-queries 切換到 mysql-pool 連接,因此用戶可以共享一個 mysql-connection,但我對此完全不熟悉(也是 nodejs/socket.io 的新手).

I'm trying to switch from single mysql-queries to mysql-pool connection, so users can share one mysql-connection, but I'm not familiar with this at all (also new to nodejs/socket.io).

以下代碼是我到目前為止每秒向數(shù)組中的套接字發(fā)送數(shù)據(jù)的代碼:

The following code is what I've done so far to send data every second to the socket in an array:

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');

但這不會向我發(fā)送任何數(shù)據(jù)到 WebSocket.這種方法(代碼結(jié)構(gòu))甚至正確嗎?以前我使用 query.on('results') 來獲取這樣的數(shù)據(jù):

But this doesn't send me any data to the WebSocket. Is this approach (code-structure) even correct? Previously I used query.on('results') to get data like this:

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 顯示數(shù)據(jù)時效果很好,但如何在我的 mysql 池連接中執(zhí)行此操作?

This worked fine showing data with auction.row but how to do this in my mysql pool connection?

另外幾秒鐘后,我收到一個錯誤,說 release() 甚至沒有定義,但它列在 mysql-module 文檔中......所以我認(rèn)為我的整個邏輯過程是不正確.

Also after some seconds I'm getting an error that release() isn't even defined, but it's listed in the mysql-module documentation... so I think my whole logical process is somehow incorrect.

  1. 我應(yīng)該使用 connection.end() 和 .release() 嗎?因為
    連接永遠(yuǎn)不應(yīng)該結(jié)束.
  2. 我還應(yīng)該使用 setInterval(function () { mysql.query('SELECT
    1');}, 5000);
    在另一個 StackOverflow 問題中回答這里的連接活著嗎?(nodejs mysql錯誤:連接丟失服務(wù)器關(guān)閉連接)
  1. Should I use connection.end() and .release() at all? Because the
    connection should never end.
  2. Should I still use setInterval(function () { mysql.query('SELECT
    1'); }, 5000);
    as answered in another StackOverflow question to keep the connection alive here? (nodejs mysql Error: Connection lost The server closed the connection)

(感謝對我的一些問題的任何提示或答案!一些答案總比沒有好,因為我體驗到這個主題根本沒有得到太多答案.)

(Appreciate any tips or answers to even some of my questions! Better some answers than none, because I experienced that this topic isn't answered much at all.)

更新了我的整個代碼(見上文).輸出現(xiàn)在看起來像這樣:http://s21.postimg.org/avsxa87rb/output.jpg

Updated my whole code (see above). Output looks like this now: http://s21.postimg.org/avsxa87rb/output.jpg

所以流獲取數(shù)據(jù),但在console.log 中什么都沒有,并且有這個javascript 錯誤?

So the stream gets the data, but in the console.log is nothing and there's this javascript error?

推薦答案

您應(yīng)該創(chuàng)建一個池,并在該池上使用 getConnection.然后,當(dāng)您完成連接時,釋放它.此外,您不需要為每個連接停止或啟動 pollingLoop,一個循環(huán)就足夠了.

You should be creating a pool, and using getConnection on that pool. Then, when you're done with the connection, release it. Additionally, you do not need to stop the pollingLoop or start it for each connection, one loop is enough.

我不理解帶條件的 if 語句,所以我省略了它.它可能需要去其他地方.

I didn't understand the if statement with conditions, so i omitted it. It likely needs to go somewhere else.

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);
    });
};

這篇關(guān)于無法將獲取的數(shù)據(jù)發(fā)送到我的 socket.io 流?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Typeorm Does not return all data(Typeorm 不返回所有數(shù)據(jù))
MySQL return extra records when using a long type number to filter varchar type(MySQL在使用長類型數(shù)字過濾varchar類型時返回額外記錄)
MySQL Error #1071 - Specified key was too long; max key length is 767 bytes(MySQL 錯誤 #1071 - 指定的鍵太長;最大密鑰長度為 767 字節(jié))
MySQL command-line table column width with utf8(MySQL命令行表列寬與utf8)
Python unicode encoding issue(Python unicode 編碼問題)
Create a MySQL stored function with a dynamic number of arguments(創(chuàng)建一個帶有動態(tài)參數(shù)數(shù)量的 MySQL 存儲函數(shù))
主站蜘蛛池模板: 避光流动池-带盖荧光比色皿-生化流动比色皿-宜兴市晶科光学仪器 东莞爱加真空科技有限公司-进口真空镀膜机|真空镀膜设备|Polycold维修厂家 | 车间除尘设备,VOCs废气处理,工业涂装流水线,伸缩式喷漆房,自动喷砂房,沸石转轮浓缩吸附,机器人喷粉线-山东创杰智慧 | 食品机械专用传感器-落料放大器-低价接近开关-菲德自控技术(天津)有限公司 | 安平县鑫川金属丝网制品有限公司,声屏障,高速声屏障,百叶孔声屏障,大弧形声屏障,凹凸穿孔声屏障,铁路声屏障,顶部弧形声屏障,玻璃钢吸音板 | 开云(中国)Kaiyun·官方网站 - 登录入口 | 品牌设计_VI设计_电影海报设计_包装设计_LOGO设计-Bacross新越品牌顾问 | 磁力轮,磁力联轴器,磁齿轮,钕铁硼磁铁-北京磁运达厂家 | 包装盒厂家_纸盒印刷_礼品盒定制-济南恒印包装有限公司 | 高空重型升降平台_高空液压举升平台_高空作业平台_移动式升降机-河南华鹰机械设备有限公司 | 我爱古诗词_古诗词名句赏析学习平台 | 磁力去毛刺机_去毛刺磁力抛光机_磁力光饰机_磁力滚抛机_精密金属零件去毛刺机厂家-冠古科技 | 小型数控车床-数控车床厂家-双头数控车床 | 电子万能试验机_液压拉力试验机_冲击疲劳试验机_材料试验机厂家-济南众标仪器设备有限公司 | 水成膜泡沫灭火剂_氟蛋白泡沫液_河南新乡骏华消防科技厂家 | 球形钽粉_球形钨粉_纳米粉末_难熔金属粉末-广东银纳官网 | 春腾云财 - 为企业提供专业财税咨询、代理记账服务 | 扒渣机,铁水扒渣机,钢水扒渣机,铁水捞渣机,钢水捞渣机-烟台盛利达工程技术有限公司 | 一体化净水器_一体化净水设备_一体化水处理设备-江苏旭浩鑫环保科技有限公司 | 2025福建平潭岛旅游攻略|蓝眼泪,景点,住宿攻略-趣平潭网 | 蒸压釜-陶粒板隔墙板蒸压釜-山东鑫泰鑫智能装备有限公司 | 超声波_清洗机_超声波清洗机专业生产厂家-深圳市好顺超声设备有限公司 | 专业广州网站建设,微信小程序开发,一物一码和NFC应用开发、物联网、外贸商城、定制系统和APP开发【致茂网络】 | 全自动五线打端沾锡机,全自动裁线剥皮双头沾锡机,全自动尼龙扎带机-东莞市海文能机械设备有限公司 | 超声骨密度仪-骨密度检测仪-经颅多普勒-tcd仪_南京科进实业有限公司 | 长沙发电机-湖南发电机-柴油发电机供应厂家-长沙明邦智能科技 | 2025世界机器人大会_IC China_半导体展_集成电路博览会_智能制造展览网 | 金属雕花板_厂家直销_价格低-山东慧诚建筑材料有限公司 | 南溪在线-南溪招聘找工作、找房子、找对象,南溪综合生活信息门户! | 河南膏药贴牌-膏药代加工-膏药oem厂家-洛阳今世康医药科技有限公司 | 鄂泉泵业官网|(杭州、上海、全国畅销)大流量防汛排涝泵-LW立式排污泵 | Type-c防水母座|贴片母座|耳机接口|Type-c插座-深圳市步步精科技有限公司 | 精密冲床,高速冲床等冲压设备生产商-常州晋志德压力机厂 | 铣刨料沥青破碎机-沥青再生料设备-RAP热再生混合料破碎筛分设备 -江苏锡宝重工 | 环保袋,无纺布袋,无纺布打孔袋,保温袋,环保袋定制,环保袋厂家,环雅包装-十七年环保袋定制厂家 | 三佳互联一站式网站建设服务|网站开发|网站设计|网站搭建服务商 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 锂电池生产厂家-电动自行车航模无人机锂电池定制-世豹新能源 | 液压升降货梯_导轨式升降货梯厂家_升降货梯厂家-河南东圣升降设备有限公司 | 间甲酚,间甲酚厂家-山东祥东新材料 | 四川职高信息网-初高中、大专、职业技术学校招生信息网 | 无缝方管|无缝矩形管|无缝方矩管|无锡方管厂家 | 扬尘在线监测系统_工地噪声扬尘检测仪_扬尘监测系统_贝塔射线扬尘监测设备「风途物联网科技」 |