很难描述这个问题 - 如果您知道更多相关术语,请进行编辑。
我正在构建一个 Web 应用程序,它基本上使用 Redis (PubSub) + Node.js + Socket.IO 作为分发服务器。
我有双向通信没有问题 - 但我需要能够从客户端(异步)向服务器发出请求并处理响应,同时仍处理可能在它之前出现的其他不相关响应。
这是我到目前为止所拥有的,但我对这种方法并不特别满意:
服务器
// 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 处理响应。