我有一个 node.js 服务器,它连接到 mysql 数据库并使用 socket.io 打开一个新套接字。该服务器的作用基本上是在数据库表中有该用户的新消息时通知连接到它的任何客户端(用户)。下面的代码仅在客户端明确发出“check_messages”请求时才有效。我该如何更改它,以便客户端是每当在该用户的 mysql 表中插入新消息时通知的客户端,而不是客户端必须显式发出“check_messages”请求?
var app = require('http').createServer().listen(8124);
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'some username',
password : 'some password',
database : 'some database'
});
connection.connect();
console.log('Server running at http://127.0.0.1:8124/');
var io = require('socket.io').listen(app);
var prev_id = 0;
io.sockets.on('connection', function (socket) {
socket.emit('greeting', 'Hello');
socket.on('check_messages',function(data){
var uid = data['uid'];
var q = "SELECT * FROM messages WHERE user_id=" + uid + " ORDER BY id DESC LIMIT 1";
connection.query(q, function(err, rows, fields) {
if (err) throw err;
if (rows[0].id > prev_id){
socket.emit('new_message',rows[0]);
prev_id = rows[0].id
}
});
});
});