linux-centos7伺服器環境下,配置swoole的非同步擴充套件ext-async-4.4.12
阿新 • • 發佈:2020-10-29
swoole版本v4.4.12,所以下載ext-async-4.4.12,git地址:https://github.com/swoole/ext-async
,自行選擇對應的版本
下載後上傳到伺服器,
zip的解壓命令是:unzip file
[root@localhost file]# cd ext-async-master [root@localhost ext-async-master]# phpize [root@localhost ext-async-master]# find / -name php-config /www/server/php/72/src/scripts/php-config /www/server/php/73/bin/php-config [root@localhost ext-async-master]# ./configure --with-php-config=/www/server/php/73/bin/php-config [root@localhost ext-async-master]# make -j 4 [root@localhost ext-async-master]# sudo make install Installing shared extensions: /www/server/php/72/lib/php/extensions/no-debug-non-zts-20170718/ [root@localhost ext-async-master]# find / -name php.ini /www/server/php/72/etc/php.ini [root@localhost ext-async-master]# vi /www/server/php/72/etc/php.ini //新增 extension=swoole_async.so [root@localhost ext-async-master]# /etc/rc.d/init.d/php-fpm-72 restart [root@localhost ext-async-master]# php -m | grep swoole swoole_async
安裝成功後有兩個demo可以學習:
建立swoole的服務端檔案server.php
<?php // 1. 建立swoole 預設建立的是一個同步的阻塞tcp服務 $host = "192.168.126.129"; // 0.0.0.0 代表接聽所有 #$host = "127.0.0.1"; // 0.0.0.0 代表接聽所有 // 建立Server物件,監聽 127.0.0.1:9501埠 // 預設是tcp $serv = new Swoole\Server($host, 9501); // 2. 註冊事件 $serv->on('Start', function($serv){ echo "啟動swoole 監聽的資訊tcp:$host:9501\n"; }); //監聽連線進入事件 $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"; }); // 3. 啟動伺服器 // 阻塞 $serv->start(); // 阻塞與非阻塞 ?>
建立swoole客戶端swoole_tcp_client.php
<?php $client = new swoole_client(SWOOLE_SOCK_TCP); // 連線到伺服器 if(!$client->connect('192.168.126.129',9501,0.5)) { die("connect failed."); } // 向伺服器傳送資料 if(!$client->send("hello world")) { die("send failed."); } // 從伺服器接受資料 $data = $client->recv(); if(!$data) { die("recv failed."); } echo $data."接收到了\n"; // 關閉連線 $client->close(); echo "這是同步客戶端.\n";
建立swoole非同步客戶端檔案swoole_async_tcp_client.php
<?php
// 非同步客戶端
use Swoole\Async\Client;
$client = new Client(SWOOLE_SOCK_TCP);
$client->on("connect",function(Client $cli){
//$cli->send("GET /HTTP/1.1 \r\n\r\n");
$cli->send("l am laohe \r\n\r\n");
});
$client->on("receive", function(Client $cli,$data){
echo "Receive:$data";
sleep(1);
$cli->send("1\n");
});
$client->on("error",function(Client $cli){
echo "error\n";
});
$client->on("close",function(Client $cli){
echo "close \n";
});
$client->connect('192.168.126.129',9501);
echo "這是非同步客戶端\n";
/*
* 訂單事務 需要時間 可以先給傳送給swoole服務端 不等待 直接返回生成成功,等swoole服務端返回結果後在返回正確的。???
*
* */