Web服務器不能向客戶端推送未經請求的數據;他們服從請求 - 響應週期。另一種方法是使用消息隊列來顯着增加複雜性。
來自客戶的投票並不是那麼糟; Web服務器擅長處理很多短的請求,並且2或3秒的輪詢間隔應該足夠快。
這是我喜歡使用的輪詢方法。它異步地等待響應再來投票前回(需要的jQuery):
function poll(url, task, progressBar, resultsCallback,
timeoutMillis, pollIntervalMillis) {
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
timeout: timeoutMillis,
data: 'action=poll&task='+task,
success: (function(response, status, xhr) {
if ('progress' in response) {
// update the UI with the progress
progressBar.setValue(response.progress);
}
if ('status' in response) {
if (response.status == 'pending') {
// task is not finished, continue polling
setTimeout((function() {
poll(url, task, progressBar, resultsCallback,
timeoutMillis, pollIntervalMillis);
}), pollIntervalMillis);
}
else {
// task completed
if (response.status == 'cancelled') {
progressBar.setColor('red');
progressBar.setText("Task '"+task+"' was cancelled");
}
else {
progressBar.setColor('green');
progressBar.setText("Task '"+task+"' complete");
}
// GET the results
$.ajax({
url: url,
type: 'GET',
timeout: timeoutMillis,
data: 'action=results&task='+task,
success: (function(response, status, xhr) {
resultsCallback(response, status, xhr);
}),
error: error
});
}
}
}),
error: error
});
function error(xhr, status, err) {
alert('Failure to communicate with server: ' + status + ', ' + err);
}
}
你的服務器端代碼應該響應民調是這樣的:
{"progress" : 42, "status" : "pending"}
你能否詳細說明或在這方面指導我一個很好的來源?我寧願不讓客戶端經常ping服務器,詢問是否完成了一個步驟。我寧願讓服務器在每個步驟結束時向客戶端發送消息。 – spots
@pot添加編輯 –