Example of php asynchronous processing task function based on swoole

  • 2021-12-13 16:35:55
  • OfStack

This paper describes the asynchronous processing task function of php based on swoole. Share it for your reference, as follows:

Install swoole:

Download the official swoole compressed package and unzip it into the directory


$ cd swoole             #  Enter  swoole  Directory 
$ phpize
$ ./configure --with-php-config=/usr/local/php/bin/php-config  # Pay attention to see if this path exists on the server 
$ make && make install

Modify the php. in file


vi /usr/local/php/lib/php.ini

Add the following


extension = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20160303/swoole.so" // Different versions may have different paths 

Restart php-fpm after saving


$ /etc/init.d/php-fpm restart

The php-m command will see if the addition is successful and you will see an swoole module


$ php -m

As a daemon monitoring task, the server creates a new server. php:


<?php
$serv = new Swoole\Server("127.0.0.1", 9502);
$serv->set(array('task_worker_num' => 4));
$serv->on('Receive', function($serv, $fd, $from_id, $data) {
  $task_id = $serv->task("Async");
  echo "Dispath AsyncTask: id=$task_id\n";
});
$serv->on('Task', function ($serv, $task_id, $from_id, $data) {
  echo "New AsyncTask[id=$task_id]".PHP_EOL;
  $serv->finish("$data -> OK");
});
$serv->on('Finish', function ($serv, $task_id, $data) {
  echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
}); 
$serv->start();

Open in command-line mode


php server.php

Create a new client. php


<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function(swoole_client $cli) {
  $cli->send("GET / HTTP/1.1\r\n\r\n");
});
$client->on("receive", function(swoole_client $cli, $data){
  echo "Receive: $data";
  $cli->send(str_repeat('A', 100)."\n");
  sleep(1);
});
$client->on("error", function(swoole_client $cli){
  echo "error\n";
});
$client->on("close", function(swoole_client $cli){
  echo "Connection close\n";
});
$client->connect('127.0.0.1', 9502);

Open a new window for command line execution


php client.php

After execution, you will find that information will be output in the window of server. php

For more readers interested in PHP related contents, please check the topics on this site: Summary of PHP Process and Thread Operation Skills, Summary of PHP Network Programming Skills, Introduction to PHP Basic Syntax, Encyclopedia of PHP Array (Array) Operation Skills, Summary of php String (string) Usage, Introduction to php+mysql Database Operation Skills and Summary of php Common Database Operation Skills

I hope this article is helpful to everyone's PHP programming.


Related articles: