1
发现难以描述此问题 - 所以如果您知道更多相关术语,请编辑。处理实时Web应用程序中服务器响应的上下文
我正在构建一个基本上使用Redis(PubSub)+ Node.js + Socket.IO作为分发服务器的Web应用程序。
我有双向沟通工作没有问题 - 但我需要能够从客户端(异步)向服务器发出请求并处理响应,同时仍处理其他可能会出现的无关响应它。
这是我到目前为止,但我不是特别满意这个办法:
服务器
// 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;博士:我需要'询问'服务器,然后使用Socket.IO处理响应。
谢谢,这基本上是我最终做到的。 – Tom 2011-04-23 13:07:47