현재 Node.js를 사용하여 채팅 시스템을 개발 중입니다. 내 질문은 Node.js를 사용하여 여러 채팅 세션을 처리하는 방법입니다. 다소 모호해서 설명해 드리겠습니다 ...Node.js로 여러 채팅 세션을 처리하는 방법
예를 들어 두 사람이 채팅 세션에 참여할 수 있습니다. Node.js는 몇 초마다 새 메시지를 확인합니다. 이 코드는 아래 코드를 사용하여 잘 작동하도록 충분히 간단합니다.
내 문제는 다른 두 사람이 동시에 다른 채팅 세션에있을 때입니다.
현재 "chat_id"및 "check_date"라는 두 개의 쿼리 문자열을 전송하므로 특정 날짜와 시간 후에 새 채팅 메시지를 확인할 수 있습니다.
문제는 "chat_id"및 "check_date"는 두 채팅방에서 서버를 사용하고 있기 때문에 새 채팅이 시작될 때마다 덮어 쓰여집니다.
나는 의미가 있습니까? 아래
내 코드 : 당신이 메시지 큐로 MySQL을 사용하려고처럼
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가보다 효과적으로 작동하도록 여러 개의 데이터 저장소를 사용하는 것이 쉬운가요? 더 이상의 제안? 그 외에도 귀하의 답변은 많은 도움이됩니다! –
@Ben 당신은 redis가 매우 빠르므로 chat 메시지를 저장하고 싶을 때, 특히 predis를 사용하여 PHP에서 redis를 사용할 수도 있고 사용해야합니다. https://github.com/nrk/predis/ – Alfred