Long polling confusion

I've been learning about long-polling and after reading a little about it, find myself a bit confused. I looked at explanations here and here

I don't quite understand what the point is in making the server sleep prior to responding. I know the idea is to try to keep the connection open between the client and server, but in the 2nd link with the highest upvoted php example, it has a code snippet where the server just calls sleep for some amount of time.

<?php
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>

What exactly does the sleep accomplish? Doesn't that just make it so that every time you send a request, it will simply sleep first (making the server do nothing), then respond, making it exactly like a standard http request but much slower? I don't see how it helps to maintain a connection if the sleep just makes the server do nothing for some amount of time. Isn't the point of long polling to respond to the client whenever new information is received?


Long polling is about the server not responding until new data is ready to be returned to the client (not sleeping for fixed durations of time).

Assume you need to get a new piece of information from a service. Your (polling) choices are: Regular polling The client sends a request in fixed intervals and requests fresh information. This is simple to implement (and potentially easy on the number of concurrent connections), but it means 1) you need to tune the interval for your use-case (how soon you need the data after it's ready), 2) you need to wait a maximum of (RTT + delay interval) for your data, 3) there is a large number of handshakes that take place

Long polling The client send a request and waits for a single response. The server thread will sleep and will be notified upon the data being available, at which point it will return them as part of that response. This means that the client will have the data in RTT / 2 time after being available. But the server needs to keep many more concurrent connections open.

链接地址: http://www.djcxy.com/p/52622.html

上一篇: 连接PHP和Flex Player

下一篇: 长期投票混乱