центральный таймер управления с использованием php любого jquery или WebSocket OR node.js

Я хочу создать центральный таймер управления с php и любым другим сценарием на стороне клиента.

введите описание изображения здесь

в основном вещи, которые нужно иметь в виду, таковы: таймер будет виден на моем веб-сайте, так что может быть сто пользователей в настоящее время вошли на мой сайт. Теперь, когда администратор перезапускает таймер в той же точке, он должен отражать все клиентские машины. поэтому базовым является необходимость синхронизировать синхронизацию всей машины.

Что я сделал

Я использовал таймер обратного отсчета клиентской стороны ( http://keith-wood.name/countdown.html ), и в фоновом режиме я вызываю ajax каждую секунду, чтобы проверить сброс нажатой или нет . но проблема заключается в том, что он не поддерживает синхронность на всех клиентских машинах . некоторое время разыгрывается между двумя машинами. Также как его реализовать?

код:

$('#shortly').countdown({until: shortly, onExpiry: liftOff, onTick: watchCountdown}); $('#shortlyStart').click(function() { shortly = new Date(); shortly.setSeconds(shortly.getSeconds() + 5.5); $('#shortly').countdown('option', {until: shortly}); }); function liftOff() { alert('We have lift off!'); } function watchCountdown(periods) { $('#monitor').text('Just ' + periods[5] + ' minutes and ' + periods[6] + ' seconds to go'); } 

timerset.php. Этот файл создает файл для серверной стороны, чтобы нажать время окончания.

 <?php $year=htmlspecialchars($_GET['year']); $month=htmlspecialchars($_GET['month']); $day=htmlspecialchars($_GET['day']); $hour=htmlspecialchars($_GET['hour']+2);//NBNBNB the +2 changes according to YOUR timezone. $minute=htmlspecialchars($_GET['minute']); $second=htmlspecialchars($_GET['second']); $timestring=$year.":".$month.":".$day.":".$hour.":".$minute.":".$second; echo $timestring."<br/>"; $filename = 'timerserver.php'; $file = fopen($filename, 'w'); rewind($file); fwrite($file,"<?php\n"); fwrite($file, "header('Content-Type: text/event-stream');\n"); fwrite($file, "header('Cache-Control: no-cache');\n"); fwrite($file, "header('connection:keep-alive');\n"); fwrite($file, "\$starttime=\"$timestring\";\n"); fwrite($file, "echo \"data:{\$starttime}\\n\\n\";\n"); fwrite($file, "ob_flush();"); fwrite($file,"flush();"); fwrite($file,"sleep(3);"); fwrite($file,"?>\n"); fflush($file); ftruncate($file, ftell($file)); fclose($file); flush(); ?> в <?php $year=htmlspecialchars($_GET['year']); $month=htmlspecialchars($_GET['month']); $day=htmlspecialchars($_GET['day']); $hour=htmlspecialchars($_GET['hour']+2);//NBNBNB the +2 changes according to YOUR timezone. $minute=htmlspecialchars($_GET['minute']); $second=htmlspecialchars($_GET['second']); $timestring=$year.":".$month.":".$day.":".$hour.":".$minute.":".$second; echo $timestring."<br/>"; $filename = 'timerserver.php'; $file = fopen($filename, 'w'); rewind($file); fwrite($file,"<?php\n"); fwrite($file, "header('Content-Type: text/event-stream');\n"); fwrite($file, "header('Cache-Control: no-cache');\n"); fwrite($file, "header('connection:keep-alive');\n"); fwrite($file, "\$starttime=\"$timestring\";\n"); fwrite($file, "echo \"data:{\$starttime}\\n\\n\";\n"); fwrite($file, "ob_flush();"); fwrite($file,"flush();"); fwrite($file,"sleep(3);"); fwrite($file,"?>\n"); fflush($file); ftruncate($file, ftell($file)); fclose($file); flush(); ?> в <?php $year=htmlspecialchars($_GET['year']); $month=htmlspecialchars($_GET['month']); $day=htmlspecialchars($_GET['day']); $hour=htmlspecialchars($_GET['hour']+2);//NBNBNB the +2 changes according to YOUR timezone. $minute=htmlspecialchars($_GET['minute']); $second=htmlspecialchars($_GET['second']); $timestring=$year.":".$month.":".$day.":".$hour.":".$minute.":".$second; echo $timestring."<br/>"; $filename = 'timerserver.php'; $file = fopen($filename, 'w'); rewind($file); fwrite($file,"<?php\n"); fwrite($file, "header('Content-Type: text/event-stream');\n"); fwrite($file, "header('Cache-Control: no-cache');\n"); fwrite($file, "header('connection:keep-alive');\n"); fwrite($file, "\$starttime=\"$timestring\";\n"); fwrite($file, "echo \"data:{\$starttime}\\n\\n\";\n"); fwrite($file, "ob_flush();"); fwrite($file,"flush();"); fwrite($file,"sleep(3);"); fwrite($file,"?>\n"); fflush($file); ftruncate($file, ftell($file)); fclose($file); flush(); ?> 

timer.php. Этот файл получает время окончания и обновляет отображаемое время.

 <html> <header> </header> <body> <script> var source = new EventSource("timerserver.php"); var mystarttime="00:00"; source.onmessage = function(event) { mystarttime=event.data; }; setInterval(function () {test(mystarttime)}, 1000); function test(intime) { var timestring=intime; var split = timestring.split(':'); var currentdate=new Date(); var finishtime=new Date(split[0],split[1]-1,split[2],split[3],split[4],split[5],0); var timediff=new Date(finishtime-currentdate); var year=timediff.getUTCFullYear(); var minutes=timediff.getUTCMinutes(); var seconds=timediff.getUTCSeconds(); var currentMinutes = ("0" + minutes).slice(-2); var currentSeconds = ("0" + seconds).slice(-2); if (year<1970) { document.getElementById("result").innerHTML="Time is up" } else document.getElementById("result").innerHTML = currentMinutes+":"+currentSeconds; } </script> <div id="result">Fetching time...</div> </body> </html> 

timerform.php. Один из способов обновления времени.

 <?php echo "<b>NB : Time is in UTC Timezone</b><br/><hr/>"; date_default_timezone_set("UTC"); $currentdatetime=date("Ymd H:i:s"); $year=date("Y"); $month=date("m"); $day=date("j"); $hour=date("H"); $minute=date("i"); $second=0; echo $currentdatetime."<hr/>"; ?> <form action="timerreset.php" method="GET"> Year <input name="year" value="<?php echo $year;?>"/><br/> Month <input name="month" value="<?php echo $month;?>"/><br/> Day <input name="day" value="<?php echo $day;?>"/><br/><br/> Hour <input name="hour" value="<?php echo $hour;?>"/><br/> Minute <input name="minute" value="<?php echo $minute+1;?>"/><br/> Second <input name="second" value="<?php echo $second;?>"/><br/> <input type="submit"/> </form> <?php flush(); ?> в <?php echo "<b>NB : Time is in UTC Timezone</b><br/><hr/>"; date_default_timezone_set("UTC"); $currentdatetime=date("Ymd H:i:s"); $year=date("Y"); $month=date("m"); $day=date("j"); $hour=date("H"); $minute=date("i"); $second=0; echo $currentdatetime."<hr/>"; ?> <form action="timerreset.php" method="GET"> Year <input name="year" value="<?php echo $year;?>"/><br/> Month <input name="month" value="<?php echo $month;?>"/><br/> Day <input name="day" value="<?php echo $day;?>"/><br/><br/> Hour <input name="hour" value="<?php echo $hour;?>"/><br/> Minute <input name="minute" value="<?php echo $minute+1;?>"/><br/> Second <input name="second" value="<?php echo $second;?>"/><br/> <input type="submit"/> </form> <?php flush(); ?> 

NB , Используйте время UTC для обслуживания разных клиентов в разных часовых поясах.

У меня есть вышеуказанный код, работающий как на моем localhost (Windows), так и на SouthCoastHosting (Linux), поэтому дайте мне знать, есть ли у вас какие-либо проблемы.

Чтобы использовать его, откройте вкладку southcoasthosting.com/timer/timerform.php и другую вкладку в southcoasthosting.com/timer/timer.php. Используйте форму таймера, чтобы изменить время окончания, и вы увидите время chage в timer.php. Из-за природы EventSource всегда будет в лучшем случае 3-секундная задержка перед обновлением таймера. В зависимости от скорости подключения вашего клиента к серверу могут быть дополнительные задержки. Я решил отправить время окончания, чтобы клиент не отставал из-за этих задержек.

Надеюсь, что все имеет смысл. Дайте мне знать иначе.

Попробуйте это вместо этого, используя серверные события HTML5.

 <?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $reset = "true"; echo "data: reset: {$reset}\n\n"; flush(); ?> 

на сервере и

 <script> var source = new EventSource("gsim_server.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; </script> <div id="result">test</div> 

на клиенте (при условии, что файл сервера находится в одной и той же папке и называется «gsim_server.php». Это всего лишь базовый пример, но вы можете использовать переданное значение, чтобы решить, сбросить или нет. Надеюсь, что это поможет.