如何经常使用 PHP 接收和发布数据



我想知道我应该怎么做才能经常使用 php 接收和发布数据。 我确切想要的是接收并发布一个整数变量,该变量每秒从服务器随机更改为客户端,并在客户端打印我的变量的值并每秒更新一次。 此问题也用于多人游戏。就像一个变量,它在页面上保存字符位置并发送和接收自身和其他玩家位置值。 我听说过一些关于解决此问题的套接字编程,但我没有找到此问题的任何好来源。 你能帮我怎么做吗.

最好的方法是使用套接字。无论如何,随着时间的推移,我已经开发出类似的东西。

此代码每秒使用服务器时间更新客户端时间:

-----------时间.php ------------

echo("{'time' : '".date('D M d Y H:i:s')."'}");

--------获取时间每秒.js ----------

function startTime(){
httpRequest= new XMLHttpRequest();
httpRequest.open("GET", "time.php",true);
httpRequest.onreadystatechange=timeLoaded;
httpRequest.send();
}
function timeLoaded(){
readyState=httpRequest.readyState;
if(readyState!=4) return;
status=httpRequest.status;
if(status!=200) return;
serverTime=httpRequest.responseText;
eval("currentime="+serverTime); //the server side variable is stored in currentime
var today=new Date(currentime.time);
hours= today.getHours();
mins = today.getminutes();
secs = today.getSeconds();
document.getElementById("time").innerHTML=h+":"+m+":"+s;
var t=setTimeout(starTime,500); //recall the function every 0.5 sec
}

-------页.html--------

<H1>Current time</H1>
<p id="time"></p>

总结:此代码每秒从服务器获取时间。"频繁"收到的变量是当前服务器时间。您可以使用此示例接收任何变量。替换

echo("{'time' : '".date('D M d Y H:i:s')."'}");

使用您想要经常接收的变量并稍微更改一下 JavaScript 代码

我希望我说得很清楚。