1. 程式人生 > >PHP擴展Swoole筆記

PHP擴展Swoole筆記

message openssl 通過 重啟 ram 信息 cli connect response

安裝Swoole擴展

通過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();

.

PHP擴展Swoole筆記