我见过的所有例子都是先查询,然后向客户发送一些信息。
如果我首先进行查询,然后在函数中使用结果,那么它可以工作:
client.query(
('SELECT * FROM '+TABLES_USERS),
function(err, results, fields) {
var Users = (results);
io.sockets.on('connection', function (socket) {
socket.on('event1', function (data) {
var requser = Users[data];
socket.emit('event2', requser);
});
});
client.end();
});
但现在我需要对客户的请求进行查询。 我试过这样的东西,但查询不起作用:
io.sockets.on('connection', function (socket) {
socket.on('event1', function (data) {
console.log('query required'); /*works*/
client.query(
('SELECT * FROM '+TABLES_USERS+' WHERE id_user ='+data),
function(err, results, fields) {
if (err) {throw err; /*doesn't work*/
console.log('error'); /*doesn't work*/ }
console.log('query is done'); /*doesn't work too. so i think query just doesn't work cuz there are no error and no results*/
socket.emit('event2', results);
client.end();
});
});
});
答案 0 :(得分:0)
在上面的例子中,有些事情你(我认为)没有做好:
1)在客户端连接到Socket.IO之后,您不要求登录,而是检查他的会话是否包含可以验证他是否已连接的数据。
您应该阅读有关Express, Socket.IO and sessions.的文章,因为它会详细解释所有内容(如果您使用的是Express)
2)我认为MongoDB,CouchDB和其他可能的数据库比MySQL更适合实时应用。
答案 1 :(得分:0)
我通过使用node-mysql-libmysqlclient而不是node-mysql解决了这个问题。但如果有人知道在node-mysql中客户端请求之后进行查询的方法,请告诉我))