我目前正在开发一个使用Node.js的聊天系统。我的问题是,如何使用Node.js处理多个聊天会话。有点含糊,所以我会解释的..。
因此,例如,两个人可能参与聊天会话。Node.js每隔几秒钟检查一次新消息。这很简单,因为我可以使用下面的代码让它工作得很好。
我的问题是当另外两个人同时在另一个聊天会话中时。
目前,我发送了两个名为"chat_id“和"check_date”的查询字符串,这样它就可以在某个日期和时间之后检查新的聊天消息。
问题是,每次开始新的聊天时,"chat_id“和"check_date”都会被覆盖,因为这两个聊天室都在使用服务器。
我说的有道理吗?
我的代码如下:
var chat_id, check_date;
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
events = require("events");
// Conntect to database
var Client = require('mysql').Client;
var client = new Client();
client.host = 'localhost';
client.port = 3306;
client.database = '****';
client.user = '****';
client.password = '****';
client.connect(function(error, results) {
if(error) {
console.log('Connection Error: ' + error.message);
return;
}
console.log('Connected to MySQL');
});
// Check for chat updates
function getChatUpdates() {
if (typeof(check_date) == 'undefined')
return;
client.query('SELECT name, message FROM chat WHERE chat_id = "' + chat_id + '" AND date_entered > "' + check_date + '"',
function selectCb(error, results, fields) {
if (error) {
console.log('GetData Error: ' + error.message);
client.end();
return;
}
if (results.length > 0) {
for(var i = 0;i<results.length;i++) {
console.log('Name: ' + results[i]['name']);
console.log('Message: ' + results[i]['message']);
}
}
});
}
// Set interval to check for chat updates every 2 seconds
setInterval(getChatUpdates, 2000);
http.createServer(function(request, response) {
// Get the query strings
var uri = url.parse(request.url, true);
chat_id = uri.query.chat_id;
check_date = uri.query.check_date;
console.log('Chat ID: ' + chat_id);
console.log('Last Check: ' + check_date);
// we'll do something here later.
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
发布于 2011-07-04 09:33:36
发布于 2011-07-04 08:43:48
var chat_id,check_date;
是全局变量。您将覆盖每个连接上的chat_id
(在createServer
中。你可能需要一些会话存储(来关联一个用户和他们的聊天),例如。数组、Redis等。
发布于 2011-07-04 08:03:36
看起来您正在尝试使用MySQL作为消息队列。RabbitMQ
https://stackoverflow.com/questions/6567572
复制