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