2017-08-30 121 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