Home > Backend Development > PHP Problem > How to implement long polling publish-subscribe pattern using PHP

How to implement long polling publish-subscribe pattern using PHP

PHPz
Release: 2023-04-05 13:35:58
Original
776 people have browsed it

In modern Web development, real-time communication has become a very important requirement, and the message queue and publish-subscribe model have become standard solutions for realizing real-time communication in Web applications. In this article, we will introduce how to use PHP to implement the long polling publish-subscribe mode.

What is long polling?

In traditional web applications, the client sends a request to the server, and the server returns a response immediately after receiving the request. Long polling is a more advanced web application architecture that allows the server to wait for a period of time after receiving a client request to determine whether there is a new message. If there is no new message, the connection will be maintained until there is a new message. When new messages arrive, a response is returned to the client.

Therefore, the implementation of long polling is more efficient than the traditional request response mode, saves server resources, and is more in line with the needs of real-time communication.

How to implement long polling using PHP?

Below we will introduce how to use PHP and message queue to implement long polling.

  1. Installing the message queue

Before using PHP to implement long polling, we need to install the message queue. Currently popular message queues include RabbitMQ, ZeroMQ and Beanstalkd. In this article, we will use Beanstalkd to implement message queues.

First, we need to download and install Beanstalkd. In Ubuntu system, you can use the following command to install:

sudo apt-get install beanstalkd

If you are in other operating systems, you can download the appropriate version from the Beanstalkd official website to install.

After the installation is complete, we can use the following command to start Beanstalkd:

sudo service beanstalkd start

  1. Write PHP code

Below, we will use an example to show how to use Beanstalkd to implement long polling in PHP.

First, connect Beanstalkd in the PHP file:

$beanstalk = new Pheanstalk('127.0.0.1');

Then, we need to define a message publishing Function:

function publish($channel, $message){

global $beanstalk;
$data = json_encode(array('channel' => $channel, 'message' => $message));
$beanstalk->useTube("pubsub")
          ->put($data, Pheanstalk::DEFAULT_PRIORITY, 0, 10);
Copy after login

}

The function of this function is to send the message to the pipe named "pubsub". We can send messages to different pipes as needed.

Then, we need to define a function to subscribe to the message:

function subscribe($channel, $callback){

global $beanstalk;
$beanstalk->watch($channel);
while (true) {
    $job = $beanstalk->reserve();
    if ($job) {
        $data = json_decode($job->getData(), true);
        if ($data['channel'] == $channel) {
            call_user_func($callback, $data['message']);
            $beanstalk->delete($job);
            break;
        } else {
            $beanstalk->bury($job);
        }
    }
}
Copy after login

}

This function Its function is to listen to the specified pipe. When a message arrives, execute the $callback function and delete the message from the queue.

Next, we need to use JavaScript code on the client side to implement long polling.

  1. Client JavaScript code

In the client, we need to define two functions. One is a function that sends messages, and the other is a function that receives messages. The following is sample code:

function publish(channel, message){

// 发送消息
$.ajax({
    type: 'POST',
    url: 'publish.php',
    data: {channel: channel, message: message},
    success: function(data){}
});
Copy after login

}

function subscribe(channel, callback){

// 接收消息
function poll(){
    $.ajax({
        type: 'GET',
        url: 'subscribe.php',
        data: 'channel=' + channel,
        dataType: 'json',
        success: function(data){
            if (data && data.message){
                callback(data.message);
            }
            poll();
        },
        error: function(){
            setTimeout(poll, 5000);
        }
    });
}
poll();
Copy after login

}

In this example, we use jQuery to send POST requests to send messages and GET requests to receive messages.

It should be noted that in long polling, the client will remain connected until it receives a response. In order for the server to not close the connection when it is idle, we need to add the following code to the page to prevent timeouts:

In this example, the page will be refreshed every 600 seconds.

Conclusion

Using PHP and message queue, we can easily implement the long polling publish-subscribe mode to achieve real-time communication needs. This method is very commonly used in real-time data exchange and communication in Web applications. It can greatly reduce the use of polling and other methods to consume server performance in applications, and improves the scalability of Web applications.

The above is the detailed content of How to implement long polling publish-subscribe pattern using PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template