Question

I'm making this as short as I can.

What I've done so far: The game I have will be running with JavaScript using setTimeout or setInterval. It's not flash or anything special. What I have made so far as like a test run (so you can understand better), is pretty much loop Ajax to keep sending requests to a PHP page as fast as it can, which then PHP reads the $_GET in the url from the request, then PHP edits a file called p1.html with the $_GET, which is simply player 1's x and y-axis coordinates. So in player 2's browser, it pretty much did what I said above, and now when it receives the Ajax request, it will receive the coordinates of player 1. So JavaScript does what it does, and moves player 1 on player 2's browser. That's what I already made myself, and I tested it and yes it works and yes it lasts forever when I fixed all the bugs and stuff.

Saying that, that's what I've made so far, but this isn't fast enough if I wanted like a online fighting game or a real time side scrolling game. So that's what I need help with. I know a lot of stuff on w3schools.com, but I just don't know how to get this job done. That's probably it. I just need browser 1, to get data to browser 2, something like this "1,100,200" or a little longer actually, and have browser 2 read that data as a variable in JavaScript (anything like x="received data";), and that's just it. JavaScript will do the rest.

I'm sure I can program everything I need myself, but for sending data from point A to point B like 50 times a second, I just don't know anything about it. Not even a name. And last, urls and examples would be very nice (to be clearer). Especially if it's already on w3schools.com (with examples) and I just missed it.

Was it helpful?

Solution

The answer is simple : Use websockets. They allow the immediate push of data in both directions for seemingly instantaneous interactions. They eliminate the need of pulling data from the client which is slow and heavy (including for the server). Note that's the solution used in my favorite game for notification push.

You might be interested by this introduction on websockets on PHP. But note that PHP really isn't the most efficient solution for long connections handling and real time games (you might prefer Go, node.js, java, etc.).

OTHER TIPS

you can use the websocket

The advantage with WebSockets (over AJAX) is basically that there's less HTTP overhead. Once the connection has been established, all future message passing is over a socket rather than new HTTP request/response calls. So, you'd assume that WebSockets can send and receive much more messages per unit time. Turns out that that's true. But there's a very bitter reality once you add latency into the mix.

WebSockets are roughly 10-20% faster than AJAX

source

what happen when we use ajax with php is

  1. it open a new connection to apache server
  2. than apache looks for php script and launch it
  3. now the php script will connect to server to query and it will return result .

but what the websocket does is that eliminate 2 connecting processes and will just send a message to the server. server is already be connected to the sql server

Another benefit is the that the connection between the client and the server stays open, the server can send messages to the client. in ajax you need to cal each time

I agree with the other posters: websockets are the technology you should use. The only drawback is that Websockets aren't supported by Internet Explorer before Version 10, which is currently only available for Windows 8 and will not be available to any Windows version prior to Windows 7. When you want to support IE users on Vista and XP, you need a fallback with AJAX or Flash.

But there is another problem you might run into:

for sending data from point A to point B like 50 times a second

When you need to send data that frequently, something seems to be wrong with your protocol. Do you plan to update the player positions at regular intervals of 20ms even though they didn't change (player is standing) or change at a constant rate (player is walking in one direction)? I would suggest you to not transfer positions but only changes in movement direction (start moving left, stop moving left at X:Y, etc.) you can safe a lot of bandwidth that way.

When architectured correctly, long polling ajax requests work just fine for non-realtime communications. That being said, long polling is more of a "hack"; if you're looking for something built with the desired connectivity in mind you choice should be websockets definitely:

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

Check out browserquest for inspiration - the fine folk at Mozilla made its entire source code available on github!

Try this: http://socket.io/

It can do websockets, long polling, flash sockets and more! And they claim that it supports IE 5.5.

Websockets are great, and have been mentioned often, but Android devices and 16% of browsers don't support websockets (CanIUse.com). Many server installations also don't support websockets, including shared LAMP setups. If you have a shared host or if you want to broad support, websockets may not be a valid option.

Long polling is the only valid alternative to websockets. It has broader support (it should work with almost all servers and clients), but it has a significant drawback on servers that don't handle many simultaneous connections well -- like Apache. Another drawback is that you have to perform many regular database queries (likely several per second) regardless of how many users are connected. Using shared memory, like shm_attach() in PHP, could ease this burden. As the server script monitors new messages, they are immediately sent through the open connection when found. The client will receive the message then restart a long connection with a new request.

If you can't use websockets, which may well be the case, you can use a long and short polling hybrid (see below). Using very long polling is unnecessary and takes up too many resources. After about 10 or 15 seconds of constant connection, you should close it and switch to old-fashioned short polling, which is just a regular GET request that is repeated.

This jQuery code is untested, but you get the idea:

function longpoll(lastid) {
    /* Start recursive long polling. The server script must stay
    connected for the 15 seconds that the client waits for a response.
    This can be done with a `while()` loop in PHP. */

    console.log("Long polling started...");

    if (typeof lastid == 'undefined') {
        lastid = 0;
    }

    //long polling...
    setTimeout(function () {
        $.ajax({
            url: "stream.php?long=1&lastid=" + lastid, success: function (payload) {
                if (payload.status == "result") {
                    //result isn't an error. lastid is used as bookmark.
                    console.log("Long poll Msg: " + payload.lastid + ": " + payload.msg);
                    longpoll(lastid); //Call the next poll recursively
                } else if (payload.status == "error") {
                    console.log("Long poll error.");
                } else {
                    console.log("Long poll no results.");
                }

                /* Now, we haven't had a message in 15 seconds. Rather than 
                reconnect by calling poll() again, just start short polling 
                by repeatedly doing an normal AJAX GET request */

                shortpoll(lastid); //start short polling after 15 seconds

            }, dataType: "json"
        });            
    }, 15000); //keep connection open for 15 seconds
};

function shortpoll(lastid) {

    console.log("Short polling started.");

    //short polling...
    var delay = 500; //start with half-second intervals
    setInterval(function () {
        console.log("setinterval started.");
        $.ajax({
            url: "stream.php?long=0&lastid=" + lastid, success: function (payload) {
                if (payload.status == "result") {
                    console.log(payload.lastid + ": " + payload.msg);
                    longpoll(lastid); //Call the next poll recursively
                } else if (payload.status == "error") {
                    console.log("Short poll error.");
                } else {
                    console.log("Short poll. No result.");
                }
            }, dataType: "json"
        });
        delay = Math.min(delay + 10, 20000) //increment but don't go over 20 seconds    
    }, delay);
}

Short polling reduces the number of concurrent connections, using repeated polling (requesting) instead. As always, the downside to short polling is the delay in getting new messages. However, this is analogous to real life, so it shouldn't be a big deal. (If somebody hasn't called you in the past week, they're not likely going to call you in the next five minutes, so checking your phone every five minutes would be silly.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top