對於這樣的任務,我會推薦你使用MongoDB和Ajax。這很簡單,只需在客戶端(html)中添加ajax代碼並在服務器端處理請求。
簡單的例子:
正常用戶發送的消息
html
文件
$.ajax({
method: "POST",
url: "http://myUrl.com/myPath",
data: { message: "Hello this is a message" },
contentType: "application/json",
success: function(data){
//handle success
},
error: function(err){
//error handler
}
})
服務器端
app.post('/myUrl', function(req, res){
if(req.body){
//message handlers here
}
Users.find({type: 'admin'}, function(err, users){
var message = req.body.message;
for(var i = 0; i < users.length, i++){
//make sure you have the type as adminPending from the schema in MongoDB
message.save(//save this message to the database); //save this message to the database as 'adminPendingType'
}
})
})
來到管理員,讓他們知道,他們已經收到一條消息,你需要給每個secon打一個ajax d,這是Facebook/Twitter如何處理大多數事情。所以基本上一次又一次地詢問服務器是否有新的收件箱。
管理員HTML
function messageGetter(){
$.ajax({
method: "POST",
url: "http://myUrl.com/didIreceiveAmessage",
data: { message: "Hello this is a message" },
contentType: "application/json",
success: function(data){
//success handler with data object
if(data['exists']== "true"){
//add your data.message to the html page, so it will be seen by the user
}
},
error: function(err){
//error handler
}
})
}
setInterval(messageGetter, 1000); //check it each second
服務器端
app.post('/myUrl', function(req, res){
if(req.body){
//message handlers here
}
Message.find({type: 'adminPending'}, function(err, messages){
//find the admin info from cookies here
if(messages.length == 0){
console.log("No messages pending");
return false; //exit the request
}else{
var admin = req.session.admin.id; //admin user
//handle stuff with admin
messages['exists'] == true;
res.send(messages);
//change the type of message from adminPending to adminSeen
return false; //exit the message
}
})
})
這是有關如何使用AJAX和MongoDB與節點做它只是一個快速簡單的例子。當然編碼將會更長,因爲你必須處理不斷變化的消息類型並保存它們。
請參閱答案 – turmuka