jquery - PHP long polling make my server hang -
i trying make facebook webpage messenger app , use ajax in client side , php on server side.
my ajax code:
function longpoll(timestamp) { var querystring = {'timestamp' : timestamp}; var shoulddelay = false; $.ajax( { type: 'get', async: true, url: 'pollmsg.php', data: querystring, timeout: 5000, cache: false } ).done(function(data){ var array = jquery.parsejson(data); (var = 0; < array.length; i++) { $('#msgtable > tbody:last-child').append('<tr><td><b>' + array[i].sender + '</b><br/>' + array[i].timestamp + '</td><td><b>' + array[i].title + '</b><br/>' + array[i].content + '</td></tr>'); } longpoll(obj.timestamp); }).fail(function(jqxhr, textstatus, errorthrown) { //shoulddelay = textstatus !== "timeout"; }).always(function() { var delay = shoulddelay ? 5000: 0; if (shoulddelay) { shoulddelay = false; window.settimeout(longpoll, delay); } }); } // initialize jquery $(function() { longpoll(); });
my php code:
//set php runtime unlimited set_time_limit(10); while (true) { $last_ajax_call = isset($_get['timestamp']) ? (int)$_get['timestamp'] : '1970-01-01 00:00:00'; $sql = "select * post (receiver = ? or sender = ?) , postat > str_to_date(?, '%y/%m/%d %h:%i:%s')"; $stmt = $conn->prepare($sql); $stmt->bind_param("sss", $username, $username, $last_ajax_call); $result = $stmt->execute(); $rows = $stmt->get_result()->fetch_all(); if (count($rows) > 0) { $result = array(); foreach ($rows $row) { $data = array ( 'sender' => $row[3], 'timestamp' => $row[5], 'title' => $row[1], 'content' => $row[2] ); array_push($result, $data); } $json = json_encode($result); echo $json; break; } else { sleep( 1 ); continue; } }
i found if once click on page ajax code, when change other page in same webserver, nginx error (as use nginx).
what problem in code? have found example of long polling , gives me similar code. thank you.
when restart php-fpm, okay, means have generated many request server cannot handle.
Comments
Post a Comment