Using PHP Message Queuing to implement Android and WEB communications

Source: Internet
Author: User
Tags end flush header implement new features socket variable thread

The requirements description is simple: Android sends data to a Web page.

System: Ubuntu 14.04 + apache2 + php5 + Android 4.4

The idea is socket + Message Queue + server send event, the following steps for the Android side, server side, front-end. The focus is on communication between PHP processes.

Android side is more direct, is a socket program. Note that if you create a socket directly inside the active main thread, you will report a android.os.NetworkOnMainThreadException, so the best way to do this is to open a thread to create the socket with the following code

    
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;
  }

And 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 close the socket when you're done

    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 is executed on the main thread.

Below is the server PHP side.

First, you 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 later $buf = Socket_read ($msgsOck, 8192);  
	
See condition break off} socket_close ($msgsock); }

is also relatively simple. This process is run independently, then open the page request data, need to access from another script, the following need to use interprocess communication, I choose Message Queue, that is, the above $msg _queue variable.

The script main program writes this.

$msg _queue_key = Ftok (__file__, ' socket '); __FILE__ refers to the current file name
$msg _queue = msg_get_queue ($msg _queue_key);//Get an existing or new message queue
Buildsocket ($msg _queue);
Socket_close ($sock);
The Ftok () function is the key that generates a queue to differentiate.

So the Handledata () task is to put the message into the queue.

function Handledata ($dataStr, $msg _queue) {
	msg_send ($msg _queue,1, $dataStr);
Socket Process Script Skeleton

 
  

As a result, other processes can find the queue through key and read the message from inside. Use this to read

function Redfromqueue ($message _queue) {
	msg_receive ($message _queue, 0, $message _type, 1024, $message, True, Msg_ ipc_nowait);
	echo $message. " \ n \ nplease ";
}

$msg _queue_key = Ftok ("socket.php", ' socket '); The first variable is the file name of the upper socket process.
$msg _queue = Msg_get_queue ($msg _queue_key, 0666);

while (true) {
	$msg _queue_status = msg_stat_queue ($msg _queue);//Get status of Message Queuing
	if ($msg _queue_status["Msg_qnum"] = = 0//If the message queue is empty at this time, skip, otherwise the blank line will be read.
		continue;
	Redfromqueue ($msg _queue);


Now is the last step, how to actively send data to the front end? This will use the new features of HTML5: Server send event (to use newer non-IE browsers, specifically view here). See the JS code directly
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;

So this is the getdata.php script that gets the data from the message queue. Just to make it recognized as a server event, you need to add a bit of formatting to the description, as follows.

 
  

You can start running the server first

PHP socket.php

You can connect using the Android device by printing listening.

Then use the Web JS request GetData script, the foreground can continue to obtain new data. Note that the message queue may be blocked (the message volume reached the upper limit), and then JS itself is the message mechanism restrictions, so lost, delay and other phenomena frequently.

The old problem with Web communications is stability. Used to hate the web QQ switch, in fact, the entire Web revolution has not been successful.



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.