Online gaming, or something faster then ajax for sending/receiving data

 ̄綄美尐妖づ 提交于 2019-11-30 03:53:38

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.).

NullPoiиteя

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.

o.v.

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!