我有一个回合制的网络应用程序,每回合限制60秒,除非他们在60秒之前结束轮次,从而开始下一个用户。
它的工作原理是通过while
语句阻止PHP页面上的数据生成,该语句检查新数据,如果存在则生成它,如果不存在则休眠和重置:
while($olddata === $newdata){
sleep(2);
/* get new data and repeat */
}
我从这些StackOverflow问题中得到了这个概念:
How do I implement basic "Long Polling"?
然而,一旦标注开始,页面就变得相对没有响应;做一些简单的事情,比如刷新页面,在超时完成或收到新数据之前不会有效。
如何配置此代码,以便在等待新数据时页面保持响应?
function draftPing(){
//This $holder element holds the data including the
//row ID, which is used to determine which turn number
//we are on
var $holder = $("#data-holder");
var currID = $holder.attr("data-currID");
$.ajax({
type: "POST",
url: "../inc/draft-ping.php",
data: { currID : currID },
async: true,
cache: false,
timeout: 60000,
success: function(data) {
var jsonData = $.parseJSON(data);
//Update $holder with new turn ID
$holder.attr("data-currID", jsonData[0]);
/* Do stuff with data */
updateDeadline(jsonData[1]);
updateTeam(jsonData[3]);
updateDraft(jsonData[4]);
/* Begin the next call for new information (wait 1s)*/
setTimeout(
draftPing,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Draft retrieve error: ", textStatus + " (" + errorThrown + ")");
setTimeout(
draftPing, /* Try again after 5s*/
5000);
}
});
}
<?php
session_start();
require_once("../config.php");
require_once("classes.php");
require_once("functions.php");
$postedID = $_POST["currID"];
$draft = new Draft($user->getLeagueID());
$currID = $draft->getCurrDraftRow();
//This is the "long polling" simulation...
//the AJAX callback won't produce any information
//until the current ID is different to the ID
//on the page with the AJAX post function
while($currID == $postedID){
sleep(2);
$currID = $draft->getCurrDraftRow();
}
/* Get all the data - redacted because it's not important (and it works) */
//Output all the data as one JSON object
exit(json_encode(array($nid, $ndeadline, $nuserid, $fteam, $fdraft)));
答案 0 :(得分:2)
如果您使用session_start()
打开会话,请在开始等待之前使用session_write_close()
将其关闭,否则将阻止所有其他请求访问会话。
<?php
session_start();
require_once("../config.php");
require_once("classes.php");
require_once("functions.php");
$postedID = $_POST["currID"];
$draft = new Draft($user->getLeagueID());
$currID = $draft->getCurrDraftRow();
//This is the "long polling" simulation...
//the AJAX callback won't produce any information
//until the current ID is different to the ID
//on the page with the AJAX post function
while($currID == $postedID){
session_write_close(); //added
sleep(2);
session_start(); //if needed, doesn't look like it is though
$currID = $draft->getCurrDraftRow();
}
/* Get all the data - redacted because it's not important (and it works) */
//Output all the data as one JSON object
exit(json_encode(array($nid, $ndeadline, $nuserid, $fteam, $fdraft)));