Swoole is an extension of PHP that can be installed and enabled through PHP extension.
Local installation
Laradock
If you install it locally, taking Laradock as an example, you need to add the following two lines in .env in the laradock directory Set the configuration value to true:
WORKSPACE_INSTALL_SWOOLE=true PHP_FPM_INSTALL_SWOOLE=true
Then run docker-compose build php-fpm workspace to rebuild the Docker container. After the build is completed, restart the two containers, enter the workspace container, and run php -m to check whether Swoole is installed successfully. , if the extension list contains swoole, the installation is successful.
Windows/Mac
If it is installed on a local Windows/Mac system, directly execute the following command to install the interface:
pecl install swoole
Simple use:
HTTP Server
First we write a simple HTTP server through Swoole, create a http_server.php file in the test directory, and write the file code as follows:
<?php // 表明服务器启动后监听本地 9051 端口 $server = new swoole_http_server('127.0.0.1', 9501); // 服务器启动时返回响应 $server->on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9501\n"; }); // 向服务器发送请求时返回响应 // 可以获取请求参数,也可以设置响应头和响应内容 $server->on("request", function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello World\n"); }); // 启动 HTTP 服务器 $server->start();
In this way, a most basic The HTTP server is completed. Its working principle is similar to that of industrial-grade Apache and Nginx servers, except that it provides the simplest server monitoring and response functions. We enable this server in the terminal:
This means that the server has been started and is listening for requests. Go to http://127.0.0.1:9501 in the browser to get the server output response content:
Recommended learning: swoole video tutorial
The above is the detailed content of How to use swoole extension. For more information, please follow other related articles on the PHP Chinese website!