


Using PHP message queue to implement Android and Web communication_PHP tutorial
Use PHP message queue to communicate between Android and Web
The requirement description is simple: Android sends data to the Web page.
System: Ubuntu 14.04 apache2 php5 Android 4.4
The idea is that the socket message queue server sends events. The following steps are Android side, server side, and front end. The focus is on PHP inter-process communication.
The Android side is relatively straightforward, it is a socket program. It should be noted that if you create a socket directly in the active main thread, an android.os.NetworkOnMainThreadException will be reported. Therefore, the best way is to open a sub-thread to create the 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地址与端口号 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 also need to close the socket after completion
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 these methods should not be executed on the main thread.
The following is the server PHP side.
First you need to run a process to receive the 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); //见后文 $buf = socket_read($msgsock, 8192); //看情况 break 掉 } socket_close($msgsock); }
It's also relatively simple. This process runs independently, so to open a web page to request data, you need to access it from another script. Next, you need to use inter-process communication. I choose the message queue, which is the $msg_queue variable above.
The main program of the script is written like this.
$msg_queue_key = ftok(__FILE__,'socket'); //__FILE__ 指当前文件名字 $msg_queue = msg_get_queue($msg_queue_key); //获取已有的或者新建一个消息队列 buildSocket($msg_queue); socket_close($sock);
Then the task of handleData() is to put the received message into the queue
function handleData($dataStr, $msg_queue){ msg_send($msg_queue,1,$dataStr); }
<!--?php //socket.php 服务器进程 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); ?-->
In this way, other processes can find this queue through key and read messages from it. Use this to make it readable
function redFromQueue($message_queue){ msg_receive($message_queue, 0, $message_type, 1024, $message, true, MSG_IPC_NOWAIT); echo $message."\n\n"; } $msg_queue_key = ftok("socket.php", 'socket'); //第一个变量为上方socket进程的文件名。 $msg_queue = msg_get_queue($msg_queue_key, 0666); while(true){ $msg_queue_status = msg_stat_queue($msg_queue); //获取消息队列的状态 if($msg_queue_status["msg_qnum"] == 0) //如果此时消息队列为空,那么跳过,否则会读取空行。 continue; redFromQueue($msg_queue); }
Now the last step is left, how to actively send data to the front end? This requires the use of a new feature of HTML5: server-sent events (to use newer non-IE browsers, see here for details). Look directly at the JS code
var source = new EventSource("php/getData.php"); //Web 服务器路径 source.onmessage = function(event){ //消息事件回调 var resData = event.data; document.getElementById("res").innerHTML=resData; };
Then this getData.php is the script above that gets data from the message queue. Just to make it recognized as a server event, you need to add some formatting instructions, as follows.
<!--?php //getData.php,提供给 Web 请求使用。 //声明文档类型 header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); function redFromQueue($message_queue){ msg_receive($message_queue, 0, $message_type, 1024, $message, true, MSG_IPC_NOWAIT); echo "data:".$message."\n\n"; //注意一定要在数据前面加上 “data:” flush(); //立刻 flush 一下 } $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); } ?-->
Now you can start running, first run the server
php socket.php
After printing listening, you can connect using an Android device.
Then use JS on the Web to request the getData script. After the request, the frontend can continuously obtain new data. It should be noted that the message queue may be blocked (the message volume reaches the upper limit), and there are limitations of the JS message mechanism itself, so losses, delays and other phenomena occur frequently.
The old problem of Web communication is stability. In the past, I always resented Web QQ for packet dropping. In fact, the entire Web revolution has not yet succeeded.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The message has been sent but rejected by the other party. This means that the sent information has been successfully sent from the device, but for some reason, the other party did not receive the message. More specifically, this is usually because the other party has set certain permissions or taken certain actions, which prevents your information from being received normally.

How to Use Swipe to Reply in iMessages on iPhone Note: The Swipe to Reply feature only works with iMessage conversations in iOS 17, not regular SMS conversations in the Messages app. Open the Messages app on your iPhone. Then, head to the iMessage conversation and simply swipe right on the iMessage you want to reply to. Once this is done, the selected iMessage will be in focus while all other messages will be blurred in the background. You'll see a text box for typing a reply and a "+" icon for accessing iMessage apps like Check-ins, Places, Stickers, Photos, and more. Just enter your message,

In iOS17, Apple has added several new features to its Messages app to make communicating with other Apple users more creative and fun. One of the features is the ability to use emojis as stickers. Stickers have been around in the Messages app for years, but so far, they haven't changed much. This is because in iOS17, Apple treats all standard emojis as stickers, allowing them to be used in the same way as actual stickers. This essentially means you're no longer limited to inserting them into conversations. Now you can also drag them anywhere on the message bubble. You can even stack them on top of each other to create little emoji scenes. The following steps show you how it works in iOS17

1. Being added to the blacklist: The message has been sent but rejected by the other party. Generally, you have been blacklisted. At this time, you will not be able to send messages to the other party, and the other party will not be able to receive your messages. 2. Network problems: If the recipient's network condition is poor or there is a network failure, the message may not be successfully received. At this point, you can try to wait for the network to return to normal before sending the message again. 3. The other party has set up Do Not Disturb: If the recipient has set up Do Not Disturb in WeChat, the sender’s messages will not be reminded or displayed within a certain period of time.

The native Messages app on iPhone lets you easily edit sent texts. This way, you can correct your mistakes, punctuation, and even autocorrect wrong phrases/words that may have been applied to your text. In this article, we will learn how to edit messages on iPhone. How to Edit Messages on iPhone Required: iPhone running iOS16 or later. You can only edit iMessage text on the Messages app, and then only within 15 minutes of sending the original text. Non-iMessage text is not supported, so they cannot be retrieved or edited. Launch the Messages app on your iPhone. In Messages, select the conversation from which you want to edit the message

Xiaomi 14Pro is a flagship model with excellent performance and configuration. It has achieved high sales since its official release. Many small functions of Xiaomi 14Pro will be ignored by everyone. For example, it can be set to light up the screen for messages. Although the function is small, , but it is very practical. Everyone will encounter various problems when using the mobile phone. So how to set up the Xiaomi 14Pro to light up the screen for messages? How to set up Xiaomi Mi 14 Pro to light up the screen for messages? Step 1: Open your phone’s Settings app. Step 2: Swipe down until you find the "Lock screen and password" option and click to enter. Step 3: In the "Lock screen & passcode" menu, find and click the "Turn on screen for notifications" option. Step 4: On the "Turn on screen when receiving notifications" page, turn on the switch to enable

Application summary of queue technology in message delay and message retry in PHP and MySQL: With the continuous development of web applications, the demand for high concurrency processing and system reliability is getting higher and higher. As a solution, queue technology is widely used in PHP and MySQL to implement message delay and message retry functions. This article will introduce the application of queue technology in PHP and MySQL, including the basic principles of queues, methods of using queues to implement message delay, and methods of using queues to implement message retries, and give

Performance Analysis and Optimization Strategy of JavaQueue Queue Summary: Queue (Queue) is one of the commonly used data structures in Java and is widely used in various scenarios. This article will discuss the performance issues of JavaQueue queues from two aspects: performance analysis and optimization strategies, and give specific code examples. Introduction Queue is a first-in-first-out (FIFO) data structure that can be used to implement producer-consumer mode, thread pool task queue and other scenarios. Java provides a variety of queue implementations, such as Arr
