Answer the question
In order to leave comments, you need to log in
How to properly send data in json to node.js client?
Hello everyone, I have a question. I want to update the news feed on socket.io, but the question arose of how to give it all in json format? and which is better to use pool or static sql?
here is server.js code
var io = require('socket.io').listen(3000),
mysql = require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'test',
port : 3306
});
// Навешиваем обработчик на подключение нового клиента
io.sockets.on('connection', function (socket) {
var time = (new Date).toLocaleTimeString();
// Посылаем клиенту сообщение о том, что он успешно подключился
socket.json.send({'event': 'connected', 'time': time});
setInterval(function() {
socket.broadcast.json.send(updateFeed());
}, 5000);
});
function updateFeed() {
pool.getConnection(function(err, connection) {
connection.query('SELECT `u`.`member`, `u`.`login`, `n`.`text`, `n`.`time` FROM `news` as `n` LEFT JOIN `members` as `u` ON (`u`.`member` = `n`.`member_id`) ORDER BY `n`.`n_id` DESC LIMIT 0, 5', function(err, rows) {
var gdata = "";
[rows].forEach(function(item, key, rows){
for(var index in item)
{
if(item.hasOwnProperty(index)) {
gdata += {
index: item[index]
};
}
}
});
return gdata;
connection.release();
});
});
};
socket = io.connect('localhost:3000');
socket.on('connect', function () {
socket.on('message', function (msg) {
console.log(msg);
});
});
Answer the question
In order to leave comments, you need to log in
var gdata = "";
gdata += { add an object to the line??? gets a line
index: item[index]
};
socket.broadcast.json.send(updateFeed() returns a string, expects an object);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question