在实时Web应用程序中处理服务器响应的上下文

发现难以描述这个问题 – 所以请编辑,如果你知道更多的相关条款。

我正在构build一个基本上使用Redis(PubSub)+ Node.js + Socket.IO作为分发服务器的Web应用程序。

我有双向沟通,没有任何问题 – 但我需要能够从客户端(asynchronous)向服务器发出请求,并处理响应,同时处理其他可能会出现的无关响应。

这是我迄今为止,但我不是特别满意这种方法:

服务器

// Lots of other code redis.psubscribe('*'); redis.on("pmessage", function(pattern, channel, message) { // broadcast }); io.on('connection', function(client) { client.on('message', function(message) { switch(message.method) { // call relevant function } }); }); function object_exists(object_id) { // do stuff to check object exists client.send({method: 'object_exists', value: object_exists}); } 

客户

 var call = Array(); $(document).ready(function() { socket.connect(); socket.on("message", function(obj){ console.log(obj); call[obj.method](obj.value); }); }); function object_exists(object_id) { socket.send({method: 'object_exists', value: object_id}); // Set a function to be called when the next server message with the 'object_exists' method is received. call['object_exists'] = function(value) { if(value) { // object does exist } } } 

tl; dr:我需要“询问”服务器,然后使用Socket.IO处理响应。

你没有具体说明你为什么不满意你的方法,但是在我看来,你几乎就在那里。 我不太确定你想要做什么,所以我只是为了清晰起见。

基本上,你只需要设置一个switch语句来充当套接字连接每一端的消息路由器,并根据传入的消息发送适当的方法。 发送足够的消息本身的状态,以便您可以处理没有任何额外的上下文的工作。 在您的重做代码中,我将object_id发送到服务器,然后再返回到客户端。

 ///SERVER // Lots of other code redis.psubscribe('*'); redis.on("pmessage", function(pattern, channel, message) { // broadcast }); io.on('connection', function(client) { client.on('message', function(message) { switch(message.method) { case 'object_exists': object_exists(message.objectId); break; } }); }); //Takes an id an returns true if the object exists function object_exists(object_id) { // do stuff to check object exists client.send({method: 'object_exists', objectId: object_id, value: object_exists}); } ///CLIENT $(document).ready(function() { //setup the message event handler for any messages coming back from the server //This won't fire right away socket.on("message", function(message){ switch(message.method) { case 'object_exists': object_exists(message.objectId, message.value); break; } }); //When we connect, send the server the message asking if object_exists socket.on("connect", function() { socket.send({method: 'object_exists', objectId: object_id}); }); //Initiate the connection socket.connect(); }); //Get's called with with objectId and a true if it exists, false if it does not function object_exists(objectId, value) { if(value) { // object does exist, do something with objectId } else { // object does not exist } } 

如果你想在同一个堆栈中看到更多的代码,可以完成类似于你所要完成的工作,请查看我的nodechat.js项目 。