0

I'm trying to redirect all users at the same time to the game page but I didn't succeed in doing that. How can I synchronize them?

I've tried using eventSource from JAVASCRIPT but still can't get them all into the game. Only one is redirected at a time. Is there any function, framework or something else that could be useful to redirect all the players at the same time?

<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML +=  " <?php startGame(); ?             >";
}
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not  support server-sent events...";
}
</script>
Auguste
  • 2,007
  • 2
  • 17
  • 25
  • 1
    php runs on the server. assuming this ` – Marc B May 31 '16 at 14:08
  • You have to setup an event handler for the messages. [For example](http://www.html5rocks.com/en/tutorials/eventsource/basics/): `source.addEventListener('message', function(e) { console.log(e.data); }, false);` – Jay Blanchard May 31 '16 at 14:09
  • you might want to consider researching about ajax requests, one of the things that allow ajax requests to be made easely is jquery [jQuery.Ajax](http://api.jquery.com/jquery.ajax/) – Giovanni Le Grand May 31 '16 at 14:10
  • You will need to use `ajax` or `websockets` along with PHP since PHP is a `server-side` programming language. – Peter May 31 '16 at 14:15
  • You can find what you are looking for by using [Ratchet](http://socketo.me/). A library for websockets in PHP. – Peter May 31 '16 at 14:17

1 Answers1

0

Your client-side javascript code should listen for your user-defined "start the game" event:

if (typeof(EventSource) !== "undefined") {
  var source = new EventSource("demo_sse.php");

  source.addEventListener("startgame", function(e) {
    // Start the game
    // e.g. document.location.href = '...';
  }, false);

} else {
  document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}

Your server's demo_sse.php needs to reply with

event: startgame\n
data: ...\n\n

Remark: You need a webserver which can deal with HTTP connection that stay open for a long time (which is what EventSource does when waiting for new events). If you use a traditional HTTP server such as Apache, the thread pool handling your HTTP requests will get filled up quickly if you do not limit the amount of concurrent players connecting to your server to only a handfull.

If your server side PHP script closes the connection after sending a reply, the client will reconnect after a timeout of 5 seconds by default. If your PHP script always closes the connection, your EventSource is downgraded to a polling mechanism with 5 second refresh interval.

le_m
  • 19,302
  • 9
  • 64
  • 74