前言:一直想学swoole,但是每次都死在新手村,环境都搭不起来,最近看视频重新学习该技术,记录学习过程,这次我在直接在服务器搭swoole环境,windows系统也不知道可不可以,反正我总是遇到各种各样的问题
安装
-
下载安装包 进入官方文档 https://wiki.swoole.com/#/environment 我用的码云下载swoole源码:(我下载的是4.7.1版本) https://gitee.com/swoole/swoole/tags -
将源码文件放置服务器  -
连接服务器,进入改swoole目录  -
从源码编译安装
-
输入命令 phpize
 -
查找php的配置文件路径 find / -name php-config
 -
继续输入编译指令(–with-php-config后面带的是前面获取的php配置文件路径,要求php=7.2 或更高版本,我这里用的是php7.2) ./configure --enable-openssl --enable-http2 --with-php-config=/www/server/php/72/bin/php-config
 -
最后再执行命令(编译时间可能比较长) make && sudo make install
 -
查看php扩展,swoole是否有安装 php -m
 -
添加 swoole 到 php.ini里 extension=swoole.so

TCP 服务器简单的使用
-
在swoole_test/TCP.php写服务端代码 <?php
class TCP{
private $server = null;
public function __construct(){
$this->server = new Swoole\Server('127.0.0.1', 9501);
$this->server->set([
'worker_num' => 4,
'max_request' => 50,
]);
$this->server->on('Connect', [$this, "onConnect"]);
$this->server->on('Receive', [$this, "onReceive"]);
$this->server->on('Close', [$this, "onClose"]);
$this->server->start();
}
public function onConnect($server, $fd){
echo "客户端id:{$fd}.\n";
}
public function onReceive($server, $fd, $reactor_id, $data){
$server->send($fd, "发送数据: {$data}");
}
public function onClose($server, $fd){
echo "客户端id: {$fd}关闭.\n";
}
}
new TCP();
-
在swoole_test/client/TCP.php写客户端代码 <?php
$scheduler = new Swoole\Coroutine\Scheduler;
$scheduler->add(function () {
$client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
echo "connect failed. Error: {$client->errCode}\n";
}
fwrite(STDOUT, "请输入:");
$res = fgets(STDIN);
$client->send($res);
echo $client->recv();
$client->close();
});
$scheduler->start();
-
开启服务端常链接  -
新建窗口开启客户端  -
测试运行  -
其他例子可以看我另一篇文章 https://blog.csdn.net/qq_36303853/article/details/119955880
如果您觉得本篇对你有帮助,可以点关注,给个赞,支持一下,过程有遇到什么问题也欢迎评论私信,进行交流
|