Use PHP message queue for Android and Web communication
Requirement Description: Android sends data to a Web page.
System: Ubuntu 14.04 + apache2 + php5 + Android 4.4
The idea is to send an event through socket + Message Queue + server. The following describes the steps: Android, server, and front-end. The focus is on the communication between PHP processes.
Android is a socket program. It should be noted that if you create a socket directly in the main thread of the activity, an android. OS. NetworkOnMainThreadException will be reported. Therefore, the best way is to open a subthread to create a socket. The Code is as follows:
Private Socket socket = null; private boolean connected = false; private PrintWriter out; private BufferedReader br; private void 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 ;}
Then, send the message.
public void sendMsg(String data){ if(!connected || socket == null) return; synchronized (socket) { try { out.println(data); } catch (Exception e) { e.printStackTrace(); } } }
You need to disable socket
private void closeSocket(){ if( socket == null) return; try { socket.close(); out.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } socket = null; connected = false; }
Note that none of these methods are executed in the main thread.
Below is the PHP server.
First, you must run a process to receive information.
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"; die;} 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"; die;} if (socket_listen ($ sock, 4) = false) {echo "socket_listen () failed :". socket_strerror (socket_last_error ()). "\ n"; die;} 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 the following document $ buf = socket_read ($ msgsock, 8192); // check the break} socket_close ($ msgsock );}
It is also relatively simple. This process runs independently. To open the webpage to request data, you need to access the data from another script. Next, you need to use inter-process communication. I select message queue, that is, the above $ msg_queue variable.
Write the script into the main program.
$ Msg_queue_key = ftok (_ FILE __, 'socket '); // _ FILE _ indicates the name of the current FILE $ msg_queue = msg_get_queue ($ msg_queue_key ); // obtain existing or new message queue buildSocket ($ msg_queue); socket_close ($ sock );
The ftok () function is used to generate the key of a queue for differentiation.
The handleData () task is to put the received message into the queue.
function handleData($dataStr, $msg_queue){msg_send($msg_queue,1,$dataStr);}
Socket process script skeleton
In this way, other processes can find the queue through the key and read the message from it. Use this readable
Function redFromQueue ($ message_queue) {msg_receive ($ message_queue, 0, $ message_type, 1024, $ message, true, MSG_IPC_NOWAIT); echo $ message. "\ n" ;}$ msg_queue_key = ftok ("socket. php ", 'socket '); // The first variable is the file name of the above socket process. $ Msg_queue = msg_get_queue ($ msg_queue_key, 0666); while (true) {$ msg_queue_status = msg_stat_queue ($ msg_queue ); // obtain the status of the Message Queue if ($ msg_queue_status ["msg_qnum"] = 0) // if the message queue is empty at this time, skip this step; otherwise, empty rows are read. Continue; redFromQueue ($ msg_queue );}
The last step is to take the initiative to send data to the front-end? This requires the HTML5 new feature: the server sends events (to use a newer Non-IE browser, please refer to here for details ). View JS Code directly
Var source = new EventSource ("php/getData. php "); // Web server path source. onmessage = function (event) {// callback var resData = event for the message event. data; document. getElementById ("res "). innerHTML = resData ;};
The getData. php script above obtains data from the message queue. Just to make it recognized as a server event, you need to add a description of the format as follows.
Run the following command: first run the server
Php socket. php
After the listening is printed, the Android device can be connected.
Then, use JavaScript on the Web to request the getData script. After the request, the foreground can continuously obtain new data. It should be noted that the Message Queue may be blocked (the message volume reaches the upper limit), and the message mechanism of JS itself is limited, so the loss and delay are frequent.
The old problem of Web communication is stability. In the past, I always hated Web QQ package loss. In fact, the entire Web revolution has not yet succeeded.