search
HomePHP FrameworkSwooleHow to use swoole in php

How to use swoole in php

Apr 09, 2020 am 10:04 AM
swoole

How to use swoole in php

phpHow to use swoole?

php The basic use of Swoole is the PHP used in the

project. However, due to the long and time-consuming task, after the front-end is submitted, the server needs to respond asynchronously.

There are many solutions for server asynchronousness, including MQ, fsocket, Swoole, etc.

Swoole is written in pure C language and provides asynchronous multi-threaded server in PHP language, asynchronous TCP/UDP network client, asynchronous MySQL, asynchronous Redis, database connection pool, AsyncTask, message queue, millisecond timer, Asynchronous file reading and writing, asynchronous DNS query. Swoole has built-in Http/WebSocket server/client and Http2.0 server.

The most important thing is that it perfectly supports the PHP language. So I used Swoole to build an asynchronous server to provide a series of tasks such as asynchronous response, push, and scheduled tasks.

Installation

Swoole is written in C language and uses compilation and installation.

The installation dependencies are:

php-5.3.10 or higher version

gcc-4.4 or higher version

make
autoconf

pcre (centos system You can execute the command: yum install pcre-devel)

Installation method:

phpize #如果命令不存在 请在前面加上php的实际路径
./configure
make 
sudo make install

After compilation is completed, you need to add extensions to php.ini

extension=swoole.so

Use

Server

class Server{
    private $serv;
    public function __construct() {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
 
            //'worker_num' => 1,  //一般设置为服务器CPU数的1-4倍
 
            'daemonize' => 1,  //以守护进程执行
            'max_request' => 10000,
            'task_worker_num' => 1,  //task进程的数量
 
            "task_ipc_mode " => 3 ,  //使用消息队列通信,并设置为争抢模式
            'open_length_check'    => true,
            'dispatch_mode'        => 1,
 
            'package_length_type'  => 'N',  //这个很关键,定位包头的
            'package_length_offset' => 0,      //第N个字节是包长度的值
            'package_body_offset'  => 4,      //第几个字节开始计算长度
 
            'package_max_length'    => 2000000,  //协议最大长度
            "log_file" => "/tmp/swoole_test.log"  //日志
 
        ));
 
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
 
    }
 
    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
 
        //放入任务队列,开始执行
        $task_id = $serv->task( $data );
 
    }
 
    public function onTask($serv,$task_id,$from_id, $data) {
      //做一些事情
 
    }

Client

class Client{
 
    private $client, $ip, $port, $params;
 
    public function __construct($ip, $port, $params)
    {
 
        $this->ip = $ip;
        $this->port = $port;
        $this->params = $params;
 
        $this->client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        $this->client->set(array(
            'open_length_check'    => true,
            'package_length_type'  => 'N',
            'package_length_offset' => 0,      //第N个字节是包长度的值
            'package_body_offset'  => 4,      //第几个字节开始计算长度
            'package_max_length'    => 2000000,  //协议最大长度
 
        ));
 
        //设置事件回调函数
 
        $this->client->on('Connect', array($this, 'onConnect'));
        $this->client->on('Receive', array($this, 'onReceive'));
        $this->client->on('Close', array($this, 'onClose'));
        $this->client->on('Error', array($this, 'onError'));
 
        //发起网络连接
        $this->client->connect($ip, $port, 3);
    }
 
    public function onReceive( $cli, $data ) {
        echo "Received: " . $data . "\n";
 
    }
 
    public function onConnect($cli) {
 
        $data = pack('N', strlen($data)) . $data;
        $cli->send($data);
        $cli->close();
 
    }
 
    public function onClose( $cli)
    {
        echo "Connection close\n";
    }
 
    public function onError()
    {
        echo "Connect failed\n";
    }
 
}

Attention issues

'open_length_check'    => true,
'package_length_type'  => 'N',
'package_length_offset' => 0,      //第N个字节是包长度的值
'package_body_offset'  => 4,      //第几个字节开始计算长度
'package_max_length'    => 2000000,  //协长度

These define frame delimitation, because Swoole’s client and server Communication is through TCP connection, so frame delimiters must be given. There are multiple frame delimitation methods. Please refer to Swoole official documentation for details. Here is a way to add length with the head.

The above is the detailed content of How to use swoole in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How can I contribute to the Swoole open-source project?How can I contribute to the Swoole open-source project?Mar 18, 2025 pm 03:58 PM

The article outlines ways to contribute to the Swoole project, including reporting bugs, submitting features, coding, and improving documentation. It discusses required skills and steps for beginners to start contributing, and how to find pressing is

How do I extend Swoole with custom modules?How do I extend Swoole with custom modules?Mar 18, 2025 pm 03:57 PM

Article discusses extending Swoole with custom modules, detailing steps, best practices, and troubleshooting. Main focus is enhancing functionality and integration.

How do I use Swoole's asynchronous I/O features?How do I use Swoole's asynchronous I/O features?Mar 18, 2025 pm 03:56 PM

The article discusses using Swoole's asynchronous I/O features in PHP for high-performance applications. It covers installation, server setup, and optimization strategies.Word count: 159

How do I configure Swoole's process isolation?How do I configure Swoole's process isolation?Mar 18, 2025 pm 03:55 PM

Article discusses configuring Swoole's process isolation, its benefits like improved stability and security, and troubleshooting methods.Character count: 159

How does Swoole's reactor model work under the hood?How does Swoole's reactor model work under the hood?Mar 18, 2025 pm 03:54 PM

Swoole's reactor model uses an event-driven, non-blocking I/O architecture to efficiently manage high-concurrency scenarios, optimizing performance through various techniques.(159 characters)

How do I troubleshoot connection issues in Swoole?How do I troubleshoot connection issues in Swoole?Mar 18, 2025 pm 03:53 PM

Article discusses troubleshooting, causes, monitoring, and prevention of connection issues in Swoole, a PHP framework.

What tools can I use to monitor Swoole's performance?What tools can I use to monitor Swoole's performance?Mar 18, 2025 pm 03:52 PM

The article discusses tools and best practices for monitoring and optimizing Swoole's performance, and troubleshooting methods for performance issues.

How do I resolve memory leaks in Swoole applications?How do I resolve memory leaks in Swoole applications?Mar 18, 2025 pm 03:51 PM

Abstract: The article discusses resolving memory leaks in Swoole applications through identification, isolation, and fixing, emphasizing common causes like improper resource management and unmanaged coroutines. Tools like Swoole Tracker and Valgrind

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools