安装

这个挺简单的

直接 pecl install swoole 即可。

socketsopensslhttp2mysqlnd 根据你的需求来搞

安装成功,默认会在 php.ini 中写入 extension=swoole.so,我这里是因为刚源码安装的 php,还未将 php.ini 文件复制并重命名,如果未自动写入,就手动去添加一下

检查是否安装成功

php -m | grep swoole

测试

<?php

// 表明服务器启动后监听本地 9051 端口
$server = new swoole_http_server('192.168.174.141', 9501);

// 服务器启动时返回响应
$server->on("start", function ($server) {
    echo "Swoole http server is started at http://192.168.174.141:9501\n";
});

// 向服务器发送请求时返回响应
// 可以获取请求参数,也可以设置响应头和响应内容
$server->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

// 启动 HTTP 服务器
$server->start();

运行,然后去浏览器访问,会输出 hello world

TCP 服务器和客户端

tcp_server.php

<?php
namespace Swoole;

// 监听本地 9503 端口,等待客户端请求
$server = new Server("192.168.174.141", 9503);
// 建立连接时输出
$server->on('connect', function ($serv, $fd){
    echo "Client:Connect.\n";
});
// 接收消息时返回内容
$server->on('receive', function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, 'Swoole: '.$data);
    $serv->close($fd);
});
// 连接关闭时输出
$server->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});
// 启动 TCP 服务器
$server->start();

tcp_client.php

<?php
namespace Swoole;

// Swoole4以后通过协程来实现异步通信
go(function () {
    $client = new Coroutine\Client(SWOOLE_SOCK_TCP);
    // 尝试与指定 TCP 服务端建立连接(IP和端口号需要与服务端保持一致,超时时间为0.5秒)
    if ($client->connect("192.168.174.141", 9503, 0.5)) {
        // 建立连接后发送内容
        $client->send("hello world\n");
        // 打印接收到的消息
        echo $client->recv();
        // 关闭连接
        $client->close();
    } else {
        echo "connect failed.";
    }
});

启动

安装出现的问题

假设 PHP 安装目录为:/usr/local/php7.4

  1. 提示 pecl 命令未找到 解决:一般是未将命令加入环境变量,加入即可 ln -s /usr/local/php7.4/bin/pecl /usr/bin/pecl

  2. 提示 phpize failed 失败

Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

ERROR: `phpize' failed

解决:yum -y install autoconf