实时networking通知服务

我一直在试图build立一个实时通知系统。

最近2天我search了很多,我相信最好和最简单的解决scheme是使用node.jssocket.io来开发它,但我不知道这些。

node.jssocket.io是一个很好的实践,使其发生?

规格

  • 将存储在数据库中的两组用户(简单用户和pipe理员)
  • 当一个简单的用户发布一些东西,该post将被发送到(所有)pipe理员
  • 如果pipe理员回复post,回复将只发送给特定的用户

有什么简单的例子或教程,以开始一些东西? 如果任何人可以发表任何例子,这将是非常有帮助的我..

对于这样的任务,我build议你使用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' } }) }) 

来到pipe理员,让他们知道他们已经收到了一个消息,你需要每秒做一个Ajax调用,这是如何处理大部分事情的Facebook / Twitter的。 所以基本上一次又一次地询问服务器是否有新的收件箱。

pipe理员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来实现Node。 当然编码将会更长,因为你必须处理不断变化的消息types并保存它们。