2017-08-30 127 views
1

我一直在試圖建立(在我自己的)實時通知系統。實時網絡通知服務

過去2天我搜索了很多,我相信最好和最簡單的解決方案是使用node.jssocket.io來開發它。但我不知道這些。

node.jssocket.io一個很好的做法,使它發生?

規格

  • 兩組用戶會被存儲在DB(簡單的用戶&管理員)
  • 當一個簡單的用戶後的東西,該職位將被sended到(全部)管理員有
  • 如果管理員回覆帖子,回覆將只發送給特定用戶

是t這裏有任何簡單的例子或教程,以開始一些事情? 如果任何人都可以發佈任何示例,它會對我很有幫助。

+0

請參閱答案 – turmuka

回答

1

對於這樣的任務,我會推薦你​​使用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與節點做它只是一個快速簡單的例子。當然編碼將會更長,因爲你必須處理不斷變化的消息類型並保存它們。

+0

抱歉回答遲到。感謝您的時間和您的帖子很多..我會考慮它。 – GeoDim

+0

謝謝@GeoDim – turmuka