PHP7 source code installation and Swoole source code compilation installation

1.1 PHP7 source code installation

1.1.1 Obtaining source code and Installation

Get the PHP7 source code at www.php.net

tar -xzvf ... /configure --prefix=/home/study/ PHPCopy the code

The source code execution file is placed in the: bin directory

PHP -m # View extension for PHP installationCopy the code

1.1.2 Simplifying command execution in PHP

Alias = The absolute path of the command

Vim /. Following alias PHP = / home/work/soft/PHP / # add source/bin/PHP. The following # noteCopy the code

Source FileName Function: Reads and executes commands in FileName in the current bash environment. This command is used to re-execute newly modified initialization documents, such as.bash_profile and.profile, etc. Note: This command is usually used with the command “. Source /etc/profile is equivalent to. /etc/profile

PHP - I | grep PHP. Ini # for PHP configuration fileCopy the code

1.2 Swoole source code compilation and installation

Get swoole source: https://gitee.com/swoole/swoole.git

Phpize is used to extend PHP modules. PHP plugins can be set up to solve the problem of not having configure

/ usr/local/PHP/bin/phpize # to this line of code that can be executed directory. / configure -- with PHP - config = / usr/local/PHP/bin/PHP - configCopy the code
 make
 make installCopy the code

Finally, you can see the swoole.so extension file in the PHP extensions directory

    

1.3 Swoole is supported in PHP7

Add: extension=swoole.so to the php.ini file to check if the extension was added successfully: php-m

Run PHP echo. PHP under swoole/examples/server to see if port 9501 is executed

netstat -anp|grep 9501
Copy the code

Two, play network communication engine (It is very important)

2.1 TCP Service &TCP Client

2.1.1 TCP service

Swoole website document: create a TCP server | create UDP server

$serv = new swoole_server("127.0.0.1", 9501); $serv->set(['worker_num' => 6, // number of worker processes, CPU 1-4 times 'max_request' => 10000,]); $serv->on('connect', function ($serv, $fd, function ($serv, $fd, function ($serv, $fd, $reactor_id)) $reactor_id) { echo "Client: {$reactor_id} - {$fd}-Connect.\n"; }); $serv->on('receive', function ($serv, $fd, $reactor_id), function ($serv, $fd, $reactor_id)) $data) { $serv->send($fd, "Server: {$reactor_id} - {$fd}".$data); }); $serv->on('close', function ($serv, $fd) {echo "Client: close.\n"; }); $serv->start();Copy the code

Test TCP server method:

  1. netstats -anp | grep 9501
  2. throughtelnetTo log in to a remote host:Telnet 127.0.0.1 9501
  3. tcpClient script

View the current number of worker processes: ps – aft | grep tcp_server. PHP

    

Tips: In order to ensure the integrity of program execution, it is recommended to set smooth restart of worker process after modifying TCP server script

2.1.2 TCP Client

Ali cloud server pit —- port is not open!!Websocket fails to connect to the server, prompting Provisional Headers are shown

    

<? $client = new swoole_client(SWOOLE_SOCK_TCP); if(! $client - > connect (" 127.0.0.1 ", 9501)) {echo "connection"; exit; } // PHP cli constant fwrite(STDOUT, "Please enter a message :"); $msg = trim(fgets(STDIN)); $client->send($MSG); $result = $client->recv(); echo $result;Copy the code

2.2 HTTP Service (The commonly used)

    

$HTTP = new swoole_http_server("0.0.0.0", 8811); // Add test 1: Function ($request, $response) {$response->cookie("singwa",' XSSSSS '); time() + 1800); // $response->end('sss'.json_encode($request->get)); / /}); / * * * * https://wiki.swoole.com/wiki/page/783.html configuration static file root directory, used with enable_static_handler. * After document_root is set and enable_STATIC_handler is set to true, the document_root will determine whether the document_root file exists in the document_root path when receiving Http requests. If the document_root file exists, the document_root file will be directly sent to the client. The onRequest callback is no longer triggered. */ $http->set( [ 'enable_static_handler' => true, 'document_root' => "/home/work/hdtocs/swoole_mooc/data", ] ); $http->on('request', function($request, $response) { //print_r($request->get); $content = [ 'date:' => date("Ymd H:i:s"), 'get:' => $request->get, 'post:' => $request->post, 'header:' => $request->header, ]; swoole_async_writefile(__DIR__."/access.log", json_encode($content).PHP_EOL, function($filename){ // todo }, FILE_APPEND); $response->cookie("singwa", "xsssss", time() + 1800); $response->end("sss". json_encode($request->get)); }); $http->start();Copy the code

2.3 WebSocket Service (Focus on)

2.3.1 Basic Overview

WebSocket protocol is a new network protocol based on TCP. It enables full-duplex communication between the browser and the server — allowing the server to actively send messages to the client

Why WebSocket

  • Defect:HTTPThe communication can only be initiated by the client

WebSocket characteristics

  1. Based on theTCPThe agreement above
  2. Low performance overhead high communication efficiency
  3. The client can communicate with any server
  4. Protocol identifierws wss
  5. Persistent network communication protocol

2.3.2 Case Implementation

2.3.2.1 Server Implementation

1. Procedure_ws_server.php

$server = new swoole_websocket_server("0.0.0.0", 9912); // Configure the static file root directory, $server->set([' enable_STATIC_handler '=> true, 'document_root' => "/home/wwwroot/www.lingyuan88.com/public/swoole/data", ] ); $server->on('open', 'onOpen'); function onOpen($server, $request) { print_r($request->fd); $server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "singwa-push-secesss"); }); $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();Copy the code

2. WebSocket service optimization, base class library object-oriented: object_ws_server.php

Class Ws {CONST HOST = "0.0.0.0"; CONST PORT = 9912; public $ws = null; public function __construct() { $this->ws = new swoole_websocket_server(self::HOST, self::PORT); // Configure the static file root directory, $this->ws->set([' enable_STATIC_handler '=> true, 'document_root' => "/home/wwwroot/www.lingyuan88.com/public/swoole/data", ] ); $this->ws->on("open", [$this, 'onOpen']); $this->ws->on("message", [$this, 'onMessage']); $this->ws->on("close", [$this, 'onClose']); $this->ws->start(); } public function onOpen($ws, $request) {print_r($request->fd); } /** * public function onMessage($ws, $param, $frame) $frame) { echo "ser-push-message:{$frame->data}\n"; $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s")); } /** * close * @param $ws * @param $fd */ public function onClose($ws, $fd) { echo "clientid:{$fd}\n"; } } $obj = new Ws();Copy the code

2.3.2.2 Client implementation

    ws_client.html

<! DOCTYPE HTML >< HTML lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1> SingWA-swoole-ws test </h1> <script> var wsUrl = "ws://120.77.206.215:9912"; var websocket = new WebSocket(wsUrl); Websocket. onOpen = function(evt) {websocket.send(" hell-sinwa "); console.log("conected-swoole-success"); } // instantiate onMessage websocket.onmessage = function(evt) {console.log("ws-server-return-data:" + evt.data); } //onclose websocket.onclose = function(evt) { console.log("close"); } //onerror websocket.onerror = function(evt, e) { console.log("error:" + evt.data); } </script> </body> </html>Copy the code

2.3.2.3 test

1. Pass the WebSocket static file directory test

    

2. Pass the HTTP service test

    

2.4 Using Asynchronous Tasks (Focus on)

Usage scenarios

  • Performing time-consuming operations (sending mail broadcasts, etc.)

Note:

  • After an asynchronous task is posted, the program continues to execute, and does not wait for the task to complete
Class Ws {CONST HOST = "0.0.0.0"; CONST PORT = 9912; public $ws = null; public function __construct() { $this->ws = new swoole_websocket_server(self::HOST, self::PORT); $this->ws->set( [ 'worker_num' => 2, 'task_worker_num' => 2, ] ); / / register Server event callback function $this - > ws - > on (" open ", [$this, 'onOpen']); $this->ws->on("message", [$this, 'onMessage']); $this->ws->on("task", [$this, 'onTask']); $this->ws->on("finish", [$this, 'onFinish']); $this->ws->on("close", [$this, 'onClose']); $this->ws->start(); } public function onOpen($ws, $request) {var_dump($request->fd); } /** * public function onMessage($ws, $param, $frame) $frame) { echo "ser-push-message:{$frame->data}\n"; // todo 10s $data = [ 'task' => 1, 'fd' => $frame->fd, ]; $ws->task($data) $ws->task($data) / / client will receive the following information immediately $ws - > push ($frame - > fd, "server - push:". The date (" Y -m - d H: I: s ")); } /** * @param $serv * @param $taskId * @param $workerId * @param $data * @return string */ public function onTask($serv, $taskId, $workerId, $data) { print_r($data); // Time-consuming scene 10s sleep(10); return "on task finish"; // Tell the worker, $data} /** * @param $data * @param $data */ public function onFinish($serv, $taskId, $data) $data) { echo "taskId:{$taskId}\n"; echo "finish-data-sucess:{$data}\n"; } /** * close * @param $ws * @param $fd */ public function onClose($ws, $fd) { echo "clientid:{$fd}\n"; } } $obj = new Ws();Copy the code

Asynchronous non-blocking I/O scenario

3.1 Asynchronous, blocking, and IO models (It is important to understand)

3.1.1 Synchronous and Asynchronous

The focus is on message notification mechanisms;

Synchronous:
After the call is issuedDoes not return immediately, but once returned, the final result is returned;

Asynchronous: After the call is made, the called party returns a message immediately, but not the final result. The called notifies the caller through status, notification mechanisms, etc., or handles the result through callback functions;

3.1.2 Blocking and Nonblocking

The focus is on the state of the caller waiting for the caller to return the result of the call.

Block:
The caller is suspended until the result of the call is returnedThe caller cannot continue until the result is returned.

Non-blocking: the caller is not suspended until the result is returned;

3.1.3 IO model

Blocking IO nonblocking IO multiplexing IO signal driven IO asynchronous IOCopy the code

The stage where I/O is actually performed is when kernel memory data is copied to process memory

3.2 Swoole Asynchronous millisecond timer

Asynchronous high precision timer, particle size is millisecond level

Function ($timer_id) {echo "tick-2000ms\n"; }); // perform the swoole_timer_after(3000, function () {echo "after 3000ms.\n"; });Copy the code

3.3 Asynchronous FILE System I/OS

Asynchronous file system IO

3.3.1 asynchronous read

/** * The file is read * __DIR__ * the file does not exist returns false * The file is opened on success returns true * The specified callback function is called after the data is read. $result = swoole_async_readfile(__DIR__."/1. TXT ", function($filename, $fileContent) { echo "filename:".$filename.PHP_EOL; // \n \r\n echo "content:".$fileContent.PHP_EOL; }); $result = Swoole\Async::readfile(__DIR__."/1.txt", function($filename, $fileContent) { echo "filename:".$filename.PHP_EOL; // \n \r\n echo "content:".$fileContent.PHP_EOL; }); var_dump($result); echo "start".PHP_EOL;Copy the code

3.3.2 Asynchronous Write (Such as Logs)

$http->on('request', function($request, $response) { $content = [ 'date:' => date("Ymd H:i:s"), 'get:' => $request->get, 'post:' => $request->post, 'header:' => $request->header, ]; swoole_async_writefile(__DIR__."/access.log", json_encode($content).PHP_EOL, function($filename){ // todo }, FILE_APPEND); $response - > end (" is the response: ". Json_encode ($request - > get)); });Copy the code

3.4 Asynchronous MySQL details

class AsyncMySql { /** * @var string */ public $dbSource = ""; Public $dbConfig = []; public function __construct() { //new swoole_mysql; $this->dbSource = new Swoole\Mysql; $this - > dbConfig = [' host '= >' 127.0.0.1 ', 'port' = > 3306, 'user' = > 'root', 'password' = > 'test', 'database' => 'test', 'charset' => 'utf8', ]; } public function update() {} public function add() {} /** * mysql execute logic * @param $id * @param $username * @return bool */ public function execute($id, $username) { $this->dbSource->connect($this->dbConfig, function($db, $result) use($id, $username) { echo "mysql-connect".PHP_EOL; if($result === false) { var_dump($db->connect_error); // todo } $sql = "select * from cmf_user where id=1"; //$sql = "update test set `username` = '".$username."' where id=".$id; // insert into // query (add select update delete) $db->query($sql, function($db, If ($result === false) {// todo var_dump($db->error); }elseif($result === true) {// add update delete // todo var_dump($db->affected_rows); }else { print_r($result); } $db->close(); }); }); return true; } } $obj = new AsyncMySql(); $flag = $obj->execute(1, 'singwa-111112'); var_dump($flag).PHP_EOL; echo "start".PHP_EOL;Copy the code

    

3.5 the asynchronous Redis

3.5.1 Environment Preparation

Swoole uses redis preconditions

  • redisservice
  • hiredislibrary
  • compileswooleNeed to add-enable-async-redis

Compile and install Hiredis

use
RedisThe client needs to be installed
hiredisLibrary, download
hiredisAfter source code, execute

make -j
sudo make install
sudo ldconfigCopy the code

Hiredis download address

Enable the asynchronous Redis client

compile
swooleWhen the
configureAdd to instruction
--enable-async-redis

[root@izwz93ee3z8wdxsujiec2oz swoole]# ./configure --with-php-config=/usr/local/php/bin/php-config --enable-async-redis
make clean
make -j
sudo make install
Copy the code

Check PHP’s swoole extension: PHP -m to see if hiredis compiled successfully and installed: PHP –ri swoole

3.5.2 Code test

$redisClient = new swoole_redis; // Swoole\Redis $redisClient->connect('127.0.0.1', 6379, function(swoole_redis $redisClient, $result) { echo "connect".PHP_EOL; var_dump($result); Redis(new redis ())->set('key',2); /*$redisClient->set('singwa_1', time(), function(swoole_redis $redisClient, $result) { var_dump($result); }); */ /*$redisClient->get('singwa_1', function(swoole_redis $redisClient, $result) { var_dump($result); $redisClient->close(); }); */ $redisClient->keys('*gw*', function(swoole_redis $redisClient, $result) { var_dump($result); $redisClient->close(); }); }); echo "start".PHP_EOL;Copy the code

Next up:Swoole start to combat (ii) : Process, memory and coroutine, Swoole perfect support ThinkPHP5, distribution Task asynchronous Task mechanism implementation

Reference tutorials:Han Tianfeng recommended Swoole to the actual combat to create a high-performance event live platform