4

I am writing an android application which uses C2DM. When a user sends some message to the server, the server replies back to the sender and forwards that message to a set of other users in the network.

The problem is, the reply to the sender is delayed until the message is forwarded to all others. This is taking a lot of time. I want the reply to be sent back to sender first and then perform the forwarding process. How can i achieve this...? If i can use parallel processing, how can i do it in PHP...? Any help would be very much appreciated :)

I have used something like this,

print(json_encode("Inserted Successfully"));//."   ".count($tags)));

while($row = mysql_fetch_row($result))
{
     $id = $row[0];
     sendMessageToUserID($id,"New Question !!",$ques_id,"yyyy");
}

But, here "Inserted Successfully" is not sent to the sender, until after the while loop is executed.

hakre
  • 178,314
  • 47
  • 389
  • 754
Kishan
  • 449
  • 5
  • 20
  • You can try to force flushing the buffer early. Note however: `Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.`. A better approach in the grander scheme of things is to let a background task (e.g. cron or some kind of work/message queue) handle the slow part asynchronously. – Frank Farmer May 01 '12 at 20:25
  • I tried using flush() after the print statement in the above code, but it made no difference. I heard cron jobs will work only on Linux, illuminate me if i am wrong. Is there any other way ? – Kishan May 01 '12 at 20:29
  • 1
    Every OS has some kind of process scheduling, e.g.: http://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron – Frank Farmer May 01 '12 at 20:30

2 Answers2

6

I don't know if this will work but you could try adding Content-Length: and Connection: close headers, and of course the explicitly flushing output.

EDIT: try this

ob_start();
//output
header("Content-Length: ".ob_get_length());
header("Connection: close");
ob_end_flush();
//do other stuff
Musa
  • 89,286
  • 16
  • 105
  • 123
  • How do i explicitly flush output ? And how will it help me here..? – Kishan May 01 '12 at 20:21
  • You can use [flush](http://www.php.net/manual/en/function.flush.php) or like Dan suggested [ob_implicit_flush](http://www.php.net/manual/en/function.ob-implicit-flush.php). What i'm thinking is if the client expects a certain amount of data and gets it shouldn't need to wait for the server to close the connection. – Musa May 01 '12 at 20:34
  • Yeah i used flush() after the print statement in the code, but it made no difference. The delay did not reduce at all. – Kishan May 01 '12 at 20:36
2

Ob-Implicit-Flush should do the trick. :)

DanRedux
  • 7,925
  • 5
  • 20
  • 41