通过pecl安装, 系统中最好已经有http2依赖
sudo pecl install swoole # 根据自己系统带了哪些模块选择, 我的系统里缺少http2和postgresql, 所以这两个没选 enable sockets supports? [no] : yes enable openssl support? [no] : yes enable http2 support? [no] : enable mysqlnd support? [no] : yes enable postgresql coroutine client support? [no] :
然后根据提示, 在php.ini里添加相应的扩展
;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; ;;;;;;;;;;;;;;;;;;;;;; ... ;extension=pdo_sqlite ;extension=pgsql ;extension=shmop extension=mongodb extension=swoole
重启php-fpm后, 在phpinfo()里就能看到swoole的信息了.
HTTP Server
<?php
$http = new swoole_http_server("127.0.0.1", 9501);
$http->on("start", function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9501\n";
});
$http->on("request", function ($request, $response) {
#print_r($request->header);
#print_r($request->get);
#print_r($request->post);
print_r($request);
$response->header("Content-Type", "text/plain");
$response->write(time());
$response->write(" Hello World\n");
$response->end();
});
$http->start();
定时器例子
新版本里面使用的是tick和after方法添加定时任务
<?php
class TimerServer
{
private $serv;
public function __construct() {
$this->serv = new swoole_server("0.0.0.0", 9501);
$this->serv->set(array(
‘worker_num‘ => 3,
‘daemonize‘ => false,
‘max_request‘ => 10000,
‘dispatch_mode‘ => 2,
‘debug_mode‘=> 1 ,
));
$this->serv->on(‘WorkerStart‘, array($this, ‘onWorkerStart‘));
$this->serv->on(‘Connect‘, array($this, ‘onConnect‘));
$this->serv->on(‘Receive‘, array($this, ‘onReceive‘));
$this->serv->on(‘Close‘, array($this, ‘onClose‘));
$this->serv->start();
}
public function onWorkerStart( $serv , $worker_id) {
echo "onWorkerStart\n";
// 只有当worker_id为0时才添加定时器,避免重复添加
if( $worker_id == 0 ) {
$serv->tick(1000, array($this,‘onTimer‘), ‘1‘);
}
}
public function onConnect( $serv, $fd, $from_id ) {
echo "Client {$fd} connect\n";
}
public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {
echo "Get Message From Client {$fd}:{$data}\n";
}
public function onClose( $serv, $fd, $from_id ) {
echo "Client {$fd} close connection\n";
}
public function onTimer($timer_id, $param) {
echo ‘Timer:‘. $timer_id . ‘ ‘ . $param . "\n";
}
}
new TimerServer();
.
原文:https://www.cnblogs.com/milton/p/10366598.html