一、环境依赖
要注意Linux
内核版本和php版本。
具体官网都有:
https://wiki.swoole.com/wiki/page/7.html
二、安装
在swoole需要的条件准备之后就可以安装,安装方式有“编译安装”或使用“PECL”安装,官网有详细的介绍:
https://wiki.swoole.com/wiki/page/6.html
下面是使用PECL安装命令:
pecl install swoole
安装完成之后,要配置php.ini
,加入:
extension=swoole.so
三、开发工具提示
https://github.com/eaglewu/swoole-ide-helper
cd 你项目根目录下
composer require --dev "eaglewu/swoole-ide-helper:dev-master"
四、Swoole简单演示
创建TCP服务器:
https://wiki.swoole.com/wiki/page/476.html
创建server.php文件,代码如下:
<?php
//创建Server对象,监听 10.211.55.15:9501端口
$serv = new swoole_server("10.211.55.15", 9501); // 10.211.55.15 是我们Swoole服务器地址
//监听连接进入事件
$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();
注意9501
端口的防火墙设置。
执行这个程序,开启服务:
php server.php
回车之后,终端命令行会“卡住”呈等待状态。。。
启动成功,可以查看9501端口已经在监听状态:
netstat -an | grep 9501
然后客户端就可以来连接服务器了,官网有介绍使用telnet
工具连接服务器。
我们还可以直接用浏览器访问一下:http://10.211.55.15:9501/
然后观察服务器 (终端命令行下),会输出:
Client: Connect.
这个字符串正是我们server.php
里echo输出的。