At the moment I can only output data of a specific key (index) with console.log(auction[index].id);
but I need the data using console.log(auction.id);
. How do I accomplish this?
I'm using nodejs and my WebSocket receives data just like this:
42["stream",{"streamArray":[[{"id":20,"pid":2,"nr":4,"price":5.73,"pe":506.08,"duration":14,"hb":361262},{"id":23,"pid":17,"nr":4,"price":5.59,"pe":189.13,"duration":7,"hb":null},{"id":12,"pid":8,"nr":3,"price":5.59,"pe":90.23,"duration":7,"hb":null}]]}]
So it's a multidimensional array. And I think there's one square bracket too much? (Right before {"id":20
for example)
This way I receive the data client-side:
var socket = io.connect('http://localhost:8000/',{'forceNew':true });
socket.on('stream', function (data) {
$.each(data.streamArray,function(index,auction){
Do I have to change the code before the data is even sent to my WebSocket or can I solve this issue client-side to receive the correct data in my variable auction
? How could I solve this?
EDIT:
This is the relevant server-side code:
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 ' + connection.threadId);
var selection =
"SELECT * FROM auctions";
var streamArray = [], lg = ''; // init of array and log variable
var query = connection.query(selection, function(err, fields, results){
for (i=0; i < fields.length; i++)
{
lg += (fields[i].id+' ('+fields[i].duration+') '+fields[i].price+'€ -');
if (somecondition)
{
// mysql update here
}
}
streamArray.push(fields);
updateSockets({ streamArray: 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); });
};
See Question&Answers more detail:
os