Using PHP Message Queuing for Android and Web communication

Source: Internet
Author: User
Tags php server
<span id="Label3"></p><p><p>The requirements description is Simple: Android sends data to a web Page.</p></p><p><p>System: Ubuntu 14.04 + apache2 + php5 + Android 4.4<br></p></p><p><p>The idea is that the socket + message Queue + server sends events, The following tutorial steps for Android, server-side, front-end. The focus is on PHP inter-process communication.</p></p><p><p>The Android side is more direct, is a socket Program. It is important to note that if you create a socket directly inside the active main thread it will report a android.os.NetworkOnMainThreadException, so the best way is to open a subroutine to create the socket, the code is as follows</p></p><pre name="code" class="java"><pre name="code" class="java"> Private Socket SOCKET = Null;private Boolean connected = false;private printwriter out;private bufferedreader br;private V OID Buildsocket () { If (socket! = Null) return; Try { socket = new socket ("223.3.68.101", 54311),//IP address and port number out = new PrintWriter ( new BufferedWriter ( New OutputStreamWriter ( socket.getoutputstream ())), true); br = new BufferedReader ( new InputStreamReader (socket.getinputstream ())); } catch (ioexception e) { E.printstacktrace (); } Connected = true; }</pre></pre><p><p>Then send a message</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> public void sendmsg (String data) { if (!connected | | socket = = Null) return; Synchronized (socket) { try { out.println (data) } catch (Exception e) { e.printstacktrace ()} } }</pre></pre><p><p></p></p><p><p>You need to close the socket when you're done</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java"> private void Closesocket () { if ( socket = = Null) return; Try { socket.close (); Out.close (); Br.close (); } Catch (ioexception e) { e.printstacktrace (); } Socket = null; Connected = false; }</pre></pre><br>Note that these methods are not executed on the main thread.<p><p></p></p><p><p><br></p></p><p><p>The following is the server PHP Side.</p></p><p><p>The first step is to run a process to receive the Information.</p></p><p><p></p></p><pre name="code" class="php">function Buildsocket ($msg _queue) {$address = "223.3.68.101"; $port = 54321; if ($sock = socket_create (af_inet, sock_ STREAM, sol_tcp)) {= = False) {echo "socket_create () failed:". Socket_strerror (socket_last_error ()). "/n";d ie;} echo "socket create\n", if (socket_set_block ($sock) = = False) {echo "socket_set_block () faild:". Socket_strerror (socket_last_error ()). "\ n"; die;} If (socket_bind ($sock, $address, $port) = = False) {echo "socket_bind () failed:". Socket_strerror (socket_last_error ()). "\ n";d ie;} If (socket_listen ($sock, 4) = = False) {echo "socket_listen () failed:". Socket_strerror (socket_last_error ()). "\ n";d ie;} Echo "listening\n"; If ($msgsock = socket_accept ($sock)) = = = False) {echo "socket_accept () failed:reason:". Socket_strerror (socket_last_error ()). "\ n"; Die } $buf = Socket_read ($msgsock, 8192); While (true) {if (strlen ($buf) > 1) handledata ($buf, $msg _queue);//see Post $buf = Socket_read ($msgsock, 8192); See Conditions break Off}socket_close ($msgsock); }</pre><br>is also relatively simple. This process is run independently, then open the Web request data, need to access from another script, the following need to use inter-process communication, I choose the message queue, that is, the above $msg _queue Variable.<p><p></p></p><p><p>The script main program writes This.</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">$msg _queue_key = Ftok (__file__, ' socket '); __FILE__ refers to the current file name $msg_queue = Msg_get_queue ($msg _queue_key); Get existing or create a new message queue Buildsocket ($msg _queue); socket_close ($sock);</pre></pre>The Ftok () function is the key that generates a queue to Differentiate.<p><p></p></p><p><p>Then the Handledata () task is to put the received messages into the Queue.</p></p><p><p></p></p><pre name="code" class="php"><pre name="code" class="php">function Handledata ($dataStr, $msg _queue) {msg_send ($msg _queue,1, $dataStr);}</pre></pre>Socket Process Script Skeleton<pre name="code" class="php"><pre name="code" class="php"><?php//socket.php Server process function Buildsocket ($msg _queue) {}function handledata ($dataStr, $msg _queue) {}set_time_ Limit (0), $msg _queue_key = Ftok (__file__, ' socket '), $msg _queue = msg_get_queue ($msg _queue_key); buildsocket ($msg _ queue); Socket_close ($sock);? ></pre></pre><p><p></p></p><p><p><br></p></p><p><p>In this way, other processes can find the queue by key and read the message from the Inside. Use this to read</p></p><p><p></p></p><pre name="code" class="php"><pre name="code" class="php">function Redfromqueue ($message _queue) {msg_receive ($message _queue, 0, $message _type, 1024x768, $message, true, msg_ipc_ NOWAIT); echo $message. " \ n ";} $msg _queue_key = Ftok ("socket.php", ' socket '); The first variable is the file name of the socket process Above. $msg _queue = Msg_get_queue ($msg _queue_key, 0666), while (true) {$msg _queue_status = msg_stat_queue ($msg _queue);// Gets the status of the message queue if ($msg _queue_status["msg_qnum"] = = 0)//if The message queue is empty at this time, then skip, otherwise the blank line will be read. Continue;redfromqueue ($msg _queue);}</pre></pre><br><br>Now is the last step, how to proactively send data to the front end? This will use the new features of HTML5: the server sends the event (to use a newer Non-IE browser, see here). Read the JS code directly<p><p></p></p><p><p></p></p><pre name="code" class="javascript"><pre name="code" class="javascript">var Source = new EventSource ("php/getdata.php"); Web Server Path source.onmessage = function (event) {//message Event callback var resdata = Event.data;document.getelementbyid ("res"). innerhtml=resdata;};</pre></pre><br>So this getdata.php is the one above the script that gets the data from the message Queue. Just to let it be recognized as a server event, you need to add a bit of formatting instructions, as Follows.<br><p><p></p></p><p><p></p></p><pre name="code" class="php"><pre name="code" class="php"><?php//getdata.php, which is provided to WEB requests for Use. Declares the document type header (' content-type:text/event-stream '); header (' cache-control:no-cache '); function Redfromqueue ($ Message_queue) {msg_receive ($message _queue, 0, $message _type, 1024x768, $message, true, msg_ipc_nowait); Echo "data:". $ Message. " \ n "; Note that you must precede the data with "data:" flush (); Flush immediately} $msg _queue_key = Ftok ("socket.php", "socket"), $msg _queue = msg_get_queue ($msg _queue_key, 0666); Echo "data : connected\n\n "; flush (); while (true) {$msg _queue_status = msg_stat_queue ($msg _queue); if ($msg _queue_status[" msg_ Qnum "] = = 0) Continue;redfromqueue ($msg _queue);}? ></pre></pre><p><p><br></p></p><p><p>You can start running the server first</p></p><p><p>PHP socket.php</p></p><p><p>The listening is printed and can be connected using an Android device.</p></p><p><p>Then use the Web JS request GetData script, The front desk can continue to obtain new data after the Request. It is important to note that Message Queuing may be blocked (the message volume reaches the upper limit), and then there is the limit of the JS itself message mechanism, so the phenomenon of loss, delay, etc. is Frequent.</p></p><p><p>The old problem with Web communication is Stability. Used to resent the web QQ swap, in fact, the entire Web revolution has not been successful.<br></p></p><p><p></p></p><p><p>Using PHP Message Queuing for Android and Web communication</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.