Pergunta

I'm pretty new to server-side web development. What I want to do is to dynamically create a web page with php (no problem for that), but in this page there is an image refresh timer that update an image through AJAX.

My goal is to dynamically modify (server-side) the refresh rate written in the generated html page based on the current request rate. In other words, if there is only one client that requests refreshes, I want it to refresh once per second. But if there are two clients, I want them to refresh less often, and so, and so (it is a local application, so I don't expect a lot of clients).

I hope I can do that with php. I don't want to overload the server CPU with the computing of this rate. I would like to be able to get it quite easily.

My server uses Apache on Linux.

Someone has an idea? A suggestion? Thanks in advance!


EDIT 1: Maybe I could log a "hit" each time a request is done? But I read that putenv() will write environment var that will be valid only during the execution of the script...?


Foi útil?

Solução

It looks like you are limiting the overall polling connections to the server. The client can be informed by the server response.

To calculate the server connection without tapping into system variables or induce much expensive I/O, you can use a heuristic: Set up memcache and increase a counter each time you get a request. Set the timeout to, say, 5 seconds. This allows you to limit the total connections within the 5-second window.

The server response then tells the client either the total count, or a simple yes/no to whether it has more connections to spare. Your client program can react accordingly.

Edit:

installing memcached and memcache extension on Ubuntu:

apt-get install php5-memcache
apt-get install memcached

Here's the documentation on how to use the memcache API.

My original strategy with a single variable won't work. You can set up multiple keys, say, channel_0, channel_1, ..., channel_9, assuming there won't be too many channels because you're returning a video feed?

Then when a connection comes in, you look for a non-busy channel, and block that for a period of time:

$memcache_obj = memcache_connect('memcache_host', 11211);
$channel=null;
for ($i=0;$i<10;$i++){
  if (memcache_get($memcache_obj,'channel_'.$channel)=='') {
    $channel=$i;
    memcache_set($memcache_obj, 'channel_'.$channel, '1', 0, 10); //block for 10 seconds
    break;
  }
}

if ($channel==null) // tell the client there's no more space
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top