Fastest communication between a Android and PHP
Hi all Im building a android application that requires data from a PHP server.
Lets say i have a text input on my web application. Whenever the users trigger a "onkeydown" i want to send the character to the Android application and my Android application will just output the current character. The web application will constantly send small "commands" to myAandroid application. I would like to know what is the fastest possible way to receive those send / receive those commands.
I see a few options on how this could be implemented.
1) My android application constantly polls the server to see if a message has been written.
2) My Android application would setup a soc开发者_JAVA百科ket server that the PHP script would connect and push the message to.
3) I guess this is extremely slow and inaccurate, but i guess i could use push notifications.
Is there any other alternatives ? and what would be the best solution?.
Push message is not slow, just inaccurate (ie. no guarantee that it will be sent). Still, it's probably faster to receive a push message than to poll the server every - say - five seconds.
If you can afford the time it's worth combining the two approach, ie push messages and regular pooling as fall back.
That said, you don't provide enough info on what you're doing, so it's difficult to suggest anything.
The fastest way would be to connect to the server, leave the connection open, and have PHP slowly stream little quantities of gibberish data until it has a real message to send. That's the fastest thing, but of course is a no-no in terms of battery usage and so on. So please explain what you're trying to do.
UPDATE to remote command a phone you need an open connection. There are many ways to do it, I'll post just a proof of concept php.
<?php
//to send a command to the phone just create a file
//named command.txt in this directory
//from any other script
set_time_limit(0);
while (true)
{
if (file_exists('command.txt'))
{
$command = file_get_contents('command.txt');
rm( 'command.txt' );
echo $command;
flush();
unset ($command);
} else {
echo asc(0); //prevent the connection to be dropped
flush();
usleep(200); //sleeps for 200 ms
}
}
?>
This example lacks many things, it's just a proof of concept on how to handle an open connection with PHP. The client side would need to strip all zero bytes and keep the rest of data downloaded. This is in absolute the fastest way to handle a 1 way remote interaction, on the other hand, will suck battery pretty fast :).
精彩评论