[Swoole] 在Ubuntu下安装、快速开始

2023-05-16

本文主要讲述在 Ubuntu 下编译安装 Swoole,并根据官方文档给出的demo进行了测试和搬运,包括:TCP服务器、UDP服务器、HTTP服务器、WebSocket服务器、异步客户端、定时器和协程相关,通过模仿官方例子领略Swoole给PHPer带来全新的编程模式和思想。

它弥补PHP在网络编程的不足。

一、说明

运行环境:win10下的 UbuntuPHP7.2Swoole4.3

参考文档: https://wiki.swoole.com/wiki/page/p-quickstart.html

博客园首发地址:https://www.cnblogs.com/reader/p/11665154.html

二、安装Swoole

  • 下载解压
sudo wget https://github.com/swoole/swoole-src/archive/v4.3.6.tar.gz
cp v4.3.6.tar.gz swoole-v4.3.6.tar.gz
tar -zxvf swoole-v4.3.6.tar.gz
cd swoole-v4.3.6
  • 安装依赖
# 根据下面的编译提示进行选择安装

sudo apt-get install php-dev
sudo apt-get install autoconf
  • 编译安装
# 根据自己 php 安装的目录
cd swoole-v4.3.6
/usr/local/php/bin/phpize
./configure
make
sudo make install

make的结果:

...
----------------------------------------------------------------------
Libraries have been installed in:
   /home/fly/swoole-src-4.3.6/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

sudo make install的结果:

Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-non-zts-20170718/
Installing header files:          /usr/local/php/include/php/
  • 配置 php.ini
# 编译安装成功后,在 php.ini 文件加入
extension=swoole.so

# extension=/usr/lib/php/20170718/swoole.so

查看是否加载 swoole扩展

php -m
  • 错误排查(可忽略)

下面错误很明显,需要指定 php-conf路径:

configure: error: Cannot find php-config. Please use --with-php-config=PATH

解决方法:

./configure --with-php-config=/usr/local/php/bin/php-config

三、快速入门

a) TCP 服务器

# 创建 php 文件
vi tcp_server.php
<?php
    //创建Server对象,监听 127.0.0.1:9501端口
    $serv = new Swoole\Server("127.0.0.1", 9501); 
    
    //监听连接进入事件
    $serv->on('Connect', function ($serv, $fd) {  
        echo "Client: Connect.\n";
    });
    
    //监听数据接收事件
    $serv->on('Receive', function ($serv, $fd, $from_id, $data) {
        $serv->send($fd, "Server: ".$data);
    });
    
    //监听连接关闭事件
    $serv->on('Close', function ($serv, $fd) {
        echo "Client: Close.\n";
    });
    
    //启动服务器
    $serv->start(); 
# 程序运行测试

# 运行 server
php tcp_server.php

# 使用telnet 测试(退出telnet:Ctrl+] 回车,输入quit 回车)
telnet 127.0.0.1 9501

b) UDP 服务器

vi udp_server.php
<?php
    //创建Server对象,监听 127.0.0.1:9502端口,类型为SWOOLE_SOCK_UDP
    $serv = new swoole_server("127.0.0.1", 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP); 
    
    //监听数据接收事件
    $serv->on('Packet', function ($serv, $data, $clientInfo) {
        $serv->sendto($clientInfo['address'], $clientInfo['port'], "Server ".$data);
        var_dump($clientInfo);
    });
    
    //启动服务器
    $serv->start(); 

# 运行
php udp_server.php

# 使用 netcat 连接
netcat -u 127.0.0.1 9502

c) HTTP 服务器

vi http_server.php
<?php
    $http = new Swoole\Http\Server("0.0.0.0", 9501);
    
    $http->on('request', function ($request, $response) {
        if ($request->server['path_info'] == '/favicon.ico' ||    $request->server['request_uri'] == '/favicon.ico') {
            return $response->end();
        }
        
        var_dump($request->get, $request->post);
        $response->header("Content-Type", "text/html; charset=utf-8");
        $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
    });
    
    $http->start();
# 程序运行测试

php http_server.php

# 浏览器访问
127.0.0.1:9501

d) WebSocket 服务器

WebSocket服务器是建立在Http服务器之上的长连接服务器,客户端首先会发送一个Http的请求与服务器进行握手。握手成功后会触发onOpen事件,表示连接已就绪,onOpen函数中可以得到$request对象,包含了Http握手的相关信息,如GET参数、Cookie、Http头信息等。

建立连接后客户端与服务器端就可以双向通信了。

vi ws_server.php
<?php
    //创建websocket服务器对象,监听0.0.0.0:9502端口
    $ws = new swoole_websocket_server("0.0.0.0", 9502);
    
    //监听WebSocket连接打开事件
    $ws->on('open', function ($ws, $request) {
        var_dump($request->fd, $request->get, $request->server);
        $ws->push($request->fd, "hello, welcome\n");
    });
    
    //监听WebSocket消息事件
    $ws->on('message', function ($ws, $frame) {
        echo "Message: {$frame->data}\n";
        $ws->push($frame->fd, "server: {$frame->data}");
    });
    
    //监听WebSocket连接关闭事件
    $ws->on('close', function ($ws, $fd) {
        echo "client-{$fd} is closed\n";
    });
    
    $ws->start();
# 程序运行

php ws_server.php
//使用浏览器JS代码如下

var wsServer = 'ws://127.0.0.1:9502';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
};

websocket.onclose = function (evt) {
    console.log("Disconnected");
};

websocket.onmessage = function (evt) {
    console.log('Retrieved data from server: ' + evt.data);
};

websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};

e) 定时器

swoole提供了类似JavaScript的setInterval/setTimeout异步高精度定时器,粒度为毫秒级。

vi timer_tick.php
//每隔2000ms触发一次
$timerId = swoole_timer_tick(2000, function ($timer_id) {
    echo "tick-2000ms\n";
});

//9000ms后执行此函数
swoole_timer_after(9000, function () use ($timerId) {
    echo "after-9000ms.\n";
    
    //清除定时器
    swoole_timer_clear($timerId);
});
php timer_tick.php

f) 同步、异步 TCP 客户端

vi tcp_client.php
<?php
    $client = new swoole_client(SWOOLE_SOCK_TCP);
    
    //连接到服务器
    if (!$client->connect('127.0.0.1', 9501, 0.5))
    {
        die("connect failed.");
    }
    //向服务器发送数据
    if (!$client->send("hello world"))
    {
        die("send failed.");
    }
    //从服务器接收数据
    $data = $client->recv();
    if (!$data)
    {
        die("recv failed.");
    }
    echo $data;
    //关闭连接
    $client->close();

# 异步只能用于cli
vi tcp_async_client.php
<?php
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
    
    //注册连接成功回调
    $client->on("connect", function($cli) {
        $cli->send("hello world\n");
    });
    
    //注册数据接收回调
    $client->on("receive", function($cli, $data){
        echo "Received: ".$data."\n";
    });
    
    //注册连接失败回调
    $client->on("error", function($cli){
        echo "Connect failed\n";
    });
    
    //注册连接关闭回调
    $client->on("close", function($cli){
        echo "Connection close\n";
    });
    
    //发起连接
    $client->connect('127.0.0.1', 9501, 0.5);

g) 协程客户端

vi xxx.php
<?php
    $http = new swoole_http_server("0.0.0.0", 9501);
    
    $http->on('request', function ($request, $response) {
        $db = new Swoole\Coroutine\MySQL();
        $db->connect([
            'host' => '127.0.0.1',
            'port' => 3306,
            'user' => 'user',
            'password' => 'pass',
            'database' => 'test',
        ]);
        $data = $db->query('select * from test_table');
        $response->end(json_encode($data));
    });
    
    $http->start();

h) 协程:并发 shell_exec

vi xxx.php
<?php
    $c = 10;
    while($c--) {
        go(function () {
            //这里使用 sleep 5 来模拟一个很长的命令
            co::exec("sleep 5");
        });
    }

i) 协程:Go + Chan + Defer

参考官方文档:
https://wiki.swoole.com/wiki/page/p-csp.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[Swoole] 在Ubuntu下安装、快速开始 的相关文章

  • unity c# 录音并保存为 mp3 或 wav 文件

    private int Frequency 61 16000 录音频率 private int BitRate 61 16 比特率 private int MicSecond 61 2 每隔2秒 xff0c 保存一下录音数据 public
  • Unity c# Application类 文件路径

    Application dataPath Assets资源文件夹的绝对路径 Application persistentDataPath 持久性的数据存储路径 xff0c 在不同平台路径不同 xff0c 但都存在 xff0c 绝对路径 Ap
  • c++ 图像RGB24旋转90度和YUV420旋转90度

    逆时针旋转90度 void RGBRotate90 anticlockwise BYTE des BYTE src int width int height if des src return int n 61 0 int linesize
  • ubuntu x86搭建 麒麟arm QT6交叉编译

    ubuntu搭建QT6交叉编译 使用QT6搭建arm交叉编译平台 编译环境准备 交叉编译器 qt源码准备 开始编译QT 使用QT6搭建arm交叉编译平台 近期项目需求开发平台是unbuntu x86 目标机器是UOS arm架构 由于需要在
  • java分解质因数

    一个数的因数就是能与别的数相乘得到这个数的数 比如30 xff0c 它的因数就是1 xff0c 2 xff0c 3 xff0c 5 xff0c 6 xff0c 10 xff0c 15 xff0c 30 质因数 xff0c 首先 xff0c
  • Mac上pip/pip3设置国内源

    pip3 config set global index url https pypi tuna tsinghua edu cn simple
  • WSL基本使用配置

    前提 相信很多同学已经体验了wsl的强大 能让win电脑上少装一个虚拟机软件 xff0c 但是原生的wsl操作窗口复制粘贴很不方便 xff0c 对于使用习惯ssh的人来说用原生的确实有些难受 xff0c 故需要配置下使用ssh进行连接操作
  • 创建ECS服务器

    阿里云服务器 作业一 xff1a ECS之初体验 xff08 Linux xff09 任务一 xff1a 创建弹性云服务器 任务二 xff1a 登录云服务器 分别使用vnc Workbench和xshell登录云服务器 任务三 xff1a
  • Python报错:ModuleNotFoundError: No module named ‘xxx‘可能的解决方案大全

    Python报错 xff1a 34 ModuleNotFoundError No module named 39 xxx 39 34 这个报错是个非常常见的报错 xff0c 几乎每个python程序员都遇到过 xff0c 导致这个报错的原因
  • 反证法证明:为什么KMP算法不会跳过(漏掉)正确的答案

    KMP算法用于在母串中查找子串的出现位置 KMP算法 xff1a 字符串匹配问题 有详细的引入过程 xff0c 很容易理解掌握 首先我们都知道 xff0c KMP算法的next数组可以指导匹配失败情况下 xff0c 子串 xff08 模式串
  • 详解介绍Selenium常用API的使用--Java语言(完整版)

    参考 xff1a http www testclass net selenium java 一共分为二十个部分 xff1a 环境安装之Java 环境安装之IntelliJ IDEA 环境安装之selenium selenium3浏览器驱动
  • 华为OD2023机试真题【字符串重新排序】

    华为OD2023机试真题 全题库点这里 题目名称 字符串重新排序 知识点 排序数组 时间限制 1s 空间限制 256M 题目描述 给定一个字符串s s包含以空格分隔的若干单词 请对s进行如下处理后输出 span class token nu
  • 解决WSL2中Vmmem内存占用过大问题

    一 问题描述 在 Windows 系统中 xff0c 感觉卡顿得厉害 查看任务管理器 xff0c 内存占用 98 而名为 Vmmem 的进程占用内存高达 2 1 GB 如图 xff1a 二 Vmmem介绍 Vmmem 进程是系统合成的一个虚
  • 5款最佳Linux桌面环境的优缺点比较

    如果你刚接触Linux xff0c 那么我确信你准花了大量的时间为你的Linux发行版选择桌面环境 你可能在想每一种桌面环境都试一下 xff0c 不过这很耗费时间 外头有好多优秀的桌面环境 这就是为什么我测评了5款最佳Linux桌面环境 x
  • vue3.2中setup语法糖<script lang=“ts“ setup>

    推荐阅读 xff1a 怎样使用 Vue 3 的 xff1c script setup xff1e 语法糖功能 南北极之间的博客 CSDN博客 在 Vue 3 中 xff0c 它引入了一个 功能 它是编译时语法糖 xff0c 用于在单个文件组
  • libc++abi.dylib`__cxa_throw:毫无预兆崩溃

    最近在接一款第三方直播api 一开始很正常 xff0c 从来调试的时候意外的出现了一下崩溃 经过一段时间的摸索 xff0c 各种找资料 xff0c 发觉是由于xcode中设置了当所有异常出现时的断点 解决办法是将all改为Objective
  • UOS安装最新 向日葵(ubuntu20.04也试用)

    下载依赖 libicu57 57 1 6 43 deb9u4 amd64 deb xff08 http mirrors aliyun com debian pool main i icu libicu57 57 1 6 43 deb9u4
  • UOS 安装 vscode

    商店安装版同官网冲突 官网下载缓慢 Selecting previously unselected package code An error occurred while applying changes An error occurre
  • org.freedesktop.timedate1: Launch helper exited

    WSL UBUNTU org freedesktop timedate1 Launch helper exited bin bash sudo hwclock w hwclock r date sudo service dbus resta
  • 扔掉 Electron,拥抱基于 Rust 开发的 Tauri

    Tauri 是什么 Tauri 是一个跨平台 GUI 框架 xff0c 与 Electron 的思想基本类似 Tauri 的前端实现也是基于 Web 系列语言 xff0c Tauri 的后端使用 Rust Tauri 可以创建体积更小 运行

随机推荐