[wp-hackers] Long Polling, Ajax and WordPress

Ryan McCue lists at rotorised.com
Tue Nov 1 01:49:11 UTC 2011


Alex Hempton-Smith wrote:
> Does anybody have any advice on how I can convert my current code, which is
> a simple 'short' poll of the server every 10 seconds, to something more
> like long-polling?

Essentially, you just want a loop which waits until something comes in.
However, you want to make sure it doesn't time out (since then, you
can't tell if there's an actual connection error or not client-side).

Server-side:

	$start = time();
	while (true) {
		$bits = get_new_bits();
		if ($bits) {
			echo json_encode($bits);
			die();
		}

		// don't wait too long
		if ((time() - $start) > 600) {
			echo '{}';
			die();
		}

		sleep(1);
	}

Client-side, pseudo-code:

	while (true) {
		$.getJSON('poll.php', function (data) {
			if (data.length == 0) {
				return;
			}

			//do stuff with data
		});
	});

Thanks,
-- 
Ryan McCue
<http://ryanmccue.info/>


More information about the wp-hackers mailing list