我目前正在使用Node.js开发聊天系统。我的问题是,我如何处理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/");
太棒了!我仍然希望存储在MySQL中,以便我可以访问来自PHP的聊天消息。使用多个数据存储是否够容易,以便NodeJS更有效地工作?还有什么建议?除此之外,您的回应会有很大帮助! –
@你可以也应该使用preis的PHP使用redis,特别是当你想存储聊天消息时,因为redis是非常快的产品=> https://github.com/nrk/predis/ – Alfred