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

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

一、说明

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

参考文档: https://wiki.swoole.com/wiki/page/p-quickstart.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

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

  1. ubuntu下安装TexLive和Texmaker

    也可以参考ubuntu14.04配置中文latex完美环境(texlive+texmaker+lyx) 设置中文字体的时候参考ubuntu 下安装 texlive 并设置 ctex 中文套装 1.首先 ...

  2. ubuntu下安装nodejs

    前言 继前几天在wins环境下使用cygwin模拟器安装nodejs出现了一些问题后,今天我决定在ubuntu下安装nodejs,安装过程非常顺利,没有报错,看来还是linux环境给力啊,由于刚接触l ...

  3. ubuntu下如何快速加密可移动存储设备

    ubuntu下可以快速加密U盘和其他移动存储设备.访问的时候会要你输入密码,这样就比较安全了. ubuntu的磁盘工具使用的是LUKS加密,虽然这个加密方法不跟其他系统兼容,但可以在其他试用GNOME ...

  4. Docker最全教程之Ubuntu下安装Docker(十四)

    前言 Ubuntu是一个以桌面应用为主的开源GNU/Linux操作系统,应用很广.本篇主要讲述Ubuntu下使用SSH远程登录并安装Docker,并且提供了Docker安装的两种方式,希望对大家有所帮 ...

  5. Ubuntu下安装JDK7(附Clojure下载)

    转:http://www.linuxidc.com/Linux/2012-10/71557.htm 首先确实不得不说,网上有很多类似Ubuntu下安装JDK7的教程.不过大都是基于JDK6的bin文件 ...

  6. Ubuntu下安装Docker,及Docker的一些常用命令操作

    1.什么是 Docker         Docker 是一个开源项目,Docker 项目的目标是实现轻量级的操作系统虚拟化解决方案.         Docker 的基础是 Linux 容器(LXC ...

  7. python3.6和pip3:Ubuntu下安装升级与踩坑之路

    本文以Ubuntu16.x系统为例,演示如何安装python3.6和相应环境.安装Python3的机器必须要能访问外网才能进行如下操作! 1. 安装方式 在Ubuntu下安装python有两种方式: ...

  8. 在Ubuntu下安装ovs-dpdk

    在Ubuntu下安装ovs-dpdk 参考资料:https://software.intel.com/zh-cn/articles/using-open-vswitch-with-dpdk-on-ub ...

  9. Ubuntu 下安装QT

    Ubuntu 下安装QT 本文使用的环境 QT Library: qt-everywhere-opensource-src-4.7.4.tar.gz QT Creator: qt-creator-li ...

随机推荐

  1. 天梯杯 L2-003. 月饼

    L2-003. 月饼 时间限制 100 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不 ...

  2. 【Offer】[66] 【构建乘积数组】

    题目描述 思路分析 测试用例 Java代码 代码链接 题目描述 给定一个数组A[0, 1, -, n-1],请构建一个数组B[0, 1, -, n-1],其中B中的元素B[i] =A[0]×A[1]× ...

  3. 【Offer】[8] 【中序遍历的下一个结点】

    题目描述 思路分析 Java代码 代码链接 题目描述 给定一棵二叉树和其中的一个结点,如何找出中序遍历顺序的下一个结点? 树中的结点除了有两个分别指向左右子结点的指针以外,还有一个指向父结点的指针. ...

  4. 012 模块1-turtle库的使用

    目录 一.概述 二.turtle库基本介绍 2.1 turtle库概述 2.2 标准库 2.3 turtle的原(wan)理(fa) 2.4 turtle的魅力 三.turtle绘图窗体布局 3.1 ...

  5. [币严区块链]交易所钱包系统如何实现USDT自动归集操作

    本文代码应用场景: 每个用户在交易所充值时,每个人都分配了独立的USDT地址,而交易所需要将所有独立的地址中USDT汇集到一个钱包地址(一般是冷钱包),从而实现资产归集与安全保障. 注意: 理解以下代 ...

  6. 接口自动化测试unittest+request+excel(一)

    注: 学习python自动化测试,需要先学习python基础,主要还是多敲代码,多联系,孰能生巧,你也会是一名合格的程序员 python基础学习: http://c.biancheng.net/pyt ...

  7. spring mvc Response header content type

    Xml代码 <bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAd ...

  8. Java第二次作业第三题

    四叶玫瑰线的图形设计:当用鼠标拖拽改变窗口大小时,四叶玫瑰线会重新绘制 package naizi; import java.awt.*; import java.awt.event.*; impor ...

  9. HTML连载38-内边距属性、外边距属性

    一.内边距属性 1.定义:边框和内容之间的距离就是内边距 2.分开写 padding-top:数字px: padding-left:数字px: padding-bottom:数字px: padding ...

  10. Win10家庭版安装Docker

    1.下载Docker Toolbox 下载地址:http://mirrors.aliyun.com/docker-toolbox/windows/docker-toolbox/ 2.安装Docker ...