我有一个php服务器文件和一个html客户机文件,html文件每500 ms
向服务器发送ajax请求以检索数据,这虽然正常工作,但会导致客户机设备上的内存和cpu使用率很高。
PHP
if(isset($_POST['id']) && $_POST['id'] != '' )
{
$id = $_POST['id'];
$select = $con->prepare("SELECT * FROM data WHERE id=?");
$select->bind_param('s', $id);
$select->execute();
$result = $select->get_result();
while($row = $result->fetch_assoc())
{
echo $row['column 1'] . "\t" . $row['column 2'] . "\n";
}
}
阿贾克斯
function send(){
var formdata = new FormData(),
id = document.getElementById('id').value;
formdata.append('id', id);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', 'server.php', true);
xhr.send(formdata);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
}
setInterval(function(){send()}, 500);
我希望找到一个替代ajax的解决方案,而不是向服务器发送大量请求并在大多数时间检索相同的数据,如果服务器可以在数据更改或更新时与客户端交互,那么效率会更高。
我不能使用php
Socket
或HttpRequest
medthods,因为它们没有安装在我的托管服务器上,我不确定后者是否有效。我唯一能想到的方法就是使用SESSIONS
。根据thisphp服务器将所有用户会话存储在服务器上的同一目录中,因此可以直接在文件中更改特定用户的会话变量。但问题是这些文件中的数据是序列化的,我不确定如何反序列化数据并重新序列化,然后保存新数据!
即使我能够找到在会话文件上存储更新的方法,我仍然需要使用setinterval来监听每个
500ms
会话的变量更改,尽管这并不理想,但就内存和CPU使用率而言,这比使用XMLHttpRequest
要好得多。那么最好的方法是什么?任何帮助都将不胜感激。
更新:
我意识到
SESSION
不起作用,因为它只能由服务器而不是客户端读取,因此我必须向服务器发送ajax请求以获取我试图避免的变量。我尝试了长时间的轮询,但遇到了很多问题,
flush
和ob_flush()
无法在我的服务器上工作,我无法更改ini
设置。当尝试无限循环时,我无法让它在数据更改时中断:if(isset($_GET['size']) && $_GET['size'] != '')
{
$size = (int)$_GET['size'];
$txt = "logs/logs.txt";
$newsize = (int)filesize($txt);
while(true) {
if($newsize !== $size) {
$data = array( "size" => filesize($txt), "content" => file_get_contents($txt));
echo json_encode($data);
break;
}
else{
$newsize = (int)filesize($txt);
usleep(400000);
}
}
}
它不断地前进,即使
logs.txt
的大小增加它不会打破!如何使其断开并在大小增加时回显数据?更新2:
结果是php在调用
filesize()
方法时缓存了文件大小,因此上述循环将无限期运行,解决方法是使用clearstatcache()
方法,它将清除存储的文件大小缓存,允许循环在文件大小更改时中断。 最佳答案
好吧,经过多次测试和长期研究,我得出结论:除非客户机先向服务器发送请求,否则php服务器永远无法直接与指定的客户机交互。
我找到的唯一可靠的解决方案是使用无限循环,它只会在数据更改时中断,这将大大减少对服务器的ajax请求的频率,从而提高性能并减少客户端设备上的内存和cpu的使用量,具体情况如下:
PHP1(处理数据更新或向数据库插入新数据):
$process = $_POST['process'];
$log = "/logs/logs.txt";
if($process == 'update'){
//execute mysqli update command and update table.
$str = "Update on " . date('d/m/Y - H:i:s') . "\n";//add some text to the logs file (can be anything just to increase the logs.text size)
file_put_content($log, $str, FILE_APPEND);//FILE_APPEND add string to the end of the file instead or replacing it's content
}
else if($process == 'insert'){
//execute mysqli insert command and add new data to table.
$str = "Added new data on" . date('d/m/Y - H:i:s') . "\n";
file_put_content($log, $str, FILE_APPEND);
}
上述代码将插入/更新数据,如果不存在,则创建文件
log.txt
,并在每次请求时向其添加其他文本。log.txt
将在稍后的无限循环“below”中使用,并在循环大小更改时中断循环。PHP2(处理读取数据请求):
if(isset($_POST['id']) && $_POST['id'] != '' && isset($_POST['size']) && $_POST['size'] != '')
{
$id = (string)$_POST['id'];
$init_size = (int)$_POST['count'];
$size = file_exists('logs/logs.txt') ? (int)filesize('logs/logs.txt') : 0;//$size is logs.txt size or 0 if logs.txt doesn't exist(not created yet).
$select = $con->prepare("SELECT * FROM data WHERE id=?");
$select->bind_param('s', $id);
while(true){ //while(true) will loop indefinitely because condition true is always met
if($init_size !== $size){
$select->execute();
$result = $select->get_result();
while($row = $result->fetch_assoc())
{
$data['rows'][] = array(
"column 1" => $row['column 1'],
"column 2" => $row['column 2'],
);
}
$data['size'] = $size;
echo json_encode($data);
break; //break the loop when condition ($init_size != $size) is met which indicates that database has been updated or new data has been added to it.
}
else{
clearstatcache(); //clears the chached filesize of log.txt
$size = file_exists('logs/logs.txt') ? (int)filesize('logs/logs.txt') : 0;
usleep(100000) //sleep for 100 ms
}
}
}
阿贾克斯:
var size = 0; //declares global variable size and set it's initial value to 0
function send(s){
var formdata = new FormData(),
id = document.getElementById('id').value;
formdata.append('id', id);
formdata.append('size', s);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', 'server.php', true);
xhr.timeout = 25000; //set timeout on xmlhttprequest to 25 sec, some servers has short execution tiemout, in my case it's 27 sec so i set the value to 25 sec.
xhr.send(formdata);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = JSON.parse(xhr.responseText);
size = data.size;
console.log(data.rows);
setTimeout(function(){send(size)}, 100); //re-initiate the request after receiving data
}
}
xhr.ontimeout = function(){
xhr.abort(); //abort the timed out xmlhttp request
setTimeout(function(){send(size)}, 100);
}
send(size);
这不是理想的解决方案,但它将我的xmlhttp请求从2/sec减少到了1/25 sec,希望有人能想出更好的解决方案。