Linux to build swoole to achieve php message push method _php instance _ script home

Linux to build swoole implementation php message push method

Updated: March 23, 2024 09:59:33 Submitted by: yin
Swoole is written in pure C language and provides asynchronous multithreaded servers in PHP language, asynchronous TCP/UDP network clients, asynchronous MySQL, and asynchronous Redis, database connection pool,AsyncTask, message queue, millisecond timer, asynchronous file read and write, asynchronous DNS query, perfect support for PHP language, this article explains the Linux to build swoole to achieve php message push method

Swoole is written in pure C language and provides asynchronous multi-threaded servers in PHP language, asynchronous TCP/UDP network clients, asynchronous MySQL, asynchronous Redis, database connection pool, AsyncTask, message queue, millisecond timer, asynchronous file read and write, asynchronous DNS query. Swoole built-in Http/WebSocket server/client, Http2.0 server, perfect support for the PHP language. This article explains how to set up swoole to implement php message push under Linux.

About swoole

Swoole is a production-oriented PHP asynchronous network communication engine that enables PHP developers to write high-performance asynchronous concurrent TCP, UDP, Unix Socket, HTTP, WebSocket services. Swoole can be widely used in the Internet, mobile communications, enterprise software, cloud computing, online games, Internet of Things (IOT), Internet of vehicles, smart home and other fields. Using PHP + Swoole as a network communication framework can greatly improve the efficiency of enterprise IT research and development teams.

Swoole is not a Framework like Zend Framework, CakePHP, Yii, symfony, ThinkPHP, etc., nor is it a project like WordPress, Drupal, Discuz, UChome, etc. Swoole's goal is to challenge top-notch frameworks such as Java frameworks, Ruby On Rails, Python DjangoPylons, and others.

Swoole, while a standard PHP extension, is actually different from regular extensions. A normal extension simply provides a library function. When the Swoole extension runs, it takes over control of PHP and enters the event loop. When an IO event occurs, the underlying layer automatically calls back the specified PHP function.

Includes the following features:

1, similar to ORM data query, provide SQL wrapper, so that MySQL SQL and PHP Array, session, Cache seamless combination.

2, App MVC hierarchical structure, effective hierarchical program structure, improve program maintainability and extensibility, low coupling, based on interface development.

3, integrate a large number of practical functions, such as convenient database operation, template operation, cache operation, system configuration, form processing, paging, data call, dictionary operation, upload processing, content editing, debugging, etc.

4, template - data reflection system, you can directly call the data in the template, provide a lot of labels, you can do not need to modify the program, only modify the template, you can achieve all kinds of website update maintenance work.

A few other features

1, Swoole contains a large number of classes, provide a large number of functional extensions, basically Web development can use the function of the class, most can be found in the Swoole framework.

2, Swoole has plug-in system, Fckeditor, Adodb, pscws Chinese segmentation, Chinese full-text index system, the latest Key-Value database idea, TokyoTyrant, can extend the function of the framework indefinitely.

Install the swoole service

1. Download swoole source code, download address: https://github.com/swoole/swoole-src/releases

2. Upload the tar package to /usr/local/src/swoole, where the installation source file is stored.

3. Decompress the source file, run tar -xvfswoole.tar

4. Go to the newly decompressed directory and enter the phpize command

5. Note: phpize is the stuff in PHP-devel that dynamically adds extensions to php, so make sure you have the PHP-devel package installed on your machine.

6. Then, enter the following commands in sequence:./configure, run compile check make, and compile swoole

7. If pcre and PCre-devel related software packages are missing, install them.

8.sudo make install

9.php.ini is generally compiled and installed successfully under etc, we also need to modify php.ini, and add swoole.so extension:

10.extension=swoole.so

11. If you enter php -m and you can view swoole, the extension is successfully installed.

Install apache to start the swoole service

(1) Test whether the installation is correct to start the swoole Php service

(2) Add server.php and client.php files to apache. The general directory is under var/www/html

(3) Open two terminals Open the two files under the directory where the two files are located, you can realize the socket long connection service.

install lsof: yum -y install lsof

Server side PHP program

class WebSocketService { private static $instance = NULL; public $tagindex = 0; public $server = null; public $office_cache = null; public $timer_arr = []; // This variable holds all timer task ids. Each client can run $timer_arr[client ID] to obtain all timers created by the client. public $conf = ['host' => '0.0.0.0', 'port' => 9999, // Port used by the service 'worker_num' => 2, // Number of worker processes started 'task_worker_num' => 8, // Number of task processes started 'is_daemonize' => 0, // Whether it is running in the background: 0 - no, 1 - yes' log_file '= >'/TMP/swoole_webSocket_server. Log ', / / log file path 'ABC' = > 0,]; public function getTagIndex() { return $this->conf['abc']; } public function setSetTagIndex($index) { $this->conf['abc'] = 100; echo $this->getTagIndex(); } public function __construct($config = []) { $this->office_cache = array('1' => '1', '3'=>'2'); $this->conf = array_merge($this->conf, (array)$config); } // static method that returns a unique instance of this class public static function getInstance(){if(empty(self::$instance)){echo "instance \n"; self::$instance=new WebSocketService(); } return self::$instance; } /** * Entry for running webSocket on the server */ public function run() {try {$this->server = new \swoole_websocket_server($this->conf['host'],$this->conf['port']); $this->server->set( [ 'worker_num' => $this->conf['worker_num'], 'task_worker_num' =>$this->conf['task_worker_num'], 'daemonize' => $this->conf['is_daemonize'], 'log_file' => $this->conf['log_file'], ] ); / / registration method list $this - > server - > on (' open ', [$this, 'open']); $this->server->on('message', [$this, 'message']); $this->server->on('task', [$this, 'task']); $this->server->on('finish', [$this, 'finish']); $this->server->on('close', [$this, 'close']); $this->server->start(); } catch (\Exception $e) { var_dump($e->getCode() . ':' . $e->getMessage()); }} /** * When establishing a socket link, Execute method * @param $server * @param $request */ public function open($server, $request) { $data = [ 'client_id' => $request->fd, 'request' => $request ]; echo 'open<<'.$data['client_id']; $this->doOpen($data); } /** * When sending a message, execute method * @param $server * @param $frame */ public function message($server, $frame) {echo "GET_mesage\n"; $data = [ 'client_id' => $frame->fd, 'data' => $frame->data, 'frame' => $frame, ]; $this->doMessage($data); } /** * Executing a task * @param $server * @param $task_id * @param $from_id * @param $data */ public function task($server, $task_id, $from_id, $data) { $data['task_id'] = $task_id; $data['from_id'] = $from_id; $this->doTask($data); } /** * Task result processing * @param $server server object * @param $taskId Task process ID * @param $data */ public function finish($server, $taskId, $data) { $data['task_id'] = $taskId; $this->doFinish($data); } /** * close link * @param $server server object * @param $client_id Unique Identifier of a client */ public function close($server, $client_id) { $data = [ 'client_id' => $client_id ]; $this->doClose($data); } /** * When the client successfully connects to the server, Triggers the method * subclass to override the method on demand * @param $data * [* 'client_id', // client unique identification * 'data', // some request data * 'frame', //swoole data *]; */ public function doOpen($data) {echo "Connection established successfully "; } /** * get Swoole Websocket Server ** @return null|\swoole_websocket_server */ public function getServer() {return $this->server; } /** * Received a message from the client, Triggers the method * subclass to override the method on demand * @param $data * [* 'client_id', // client unique identification * 'data', // client sent message (data) * 'frame', //swoole data *]; */ public function doMessage($data) { $info = json_decode($data['data'],true); $officeid = $info['officeid']; $client_id = $data['client_id']; echo"<<<<".$officeid.">>>>".$client_id."\r\n"; if ($officeid == 1) {$this->sendMsgToClient('2',array('msg' =>' I am site 1 to send you data ')); } else {$this->sendMsgToClient('1',array('msg' =>' I am site 3 to send you data ')); }} /** * Specific job tasks. Need to pass $this->doJob() to trigger * subclasses to override this method on demand * @param $data * [* 'client_id', // client unique identifier *]; */ public function doTask($data) {} /** ** Result processing of work. * Subclasses override this method on demand * @param $data * [* 'client_id', // client unique identifier *]; */ public function doFinish($data) {} /** ** This method is triggered automatically when the client disconnection * Subclasses override this method on demand * @param $data * [* 'client_id', // Client unique identifier *]; */ public function doClose($data) {} /** * Send task * @param $data must be an array, $data['client_id'] */ public function doJob($data) {$this->server->task($data); } public function finishJob($data) { $this->server->finish($data); } /** * Send a message to the client * @param $client_id * @param $msg */ public function sendMsgToClient($client_id, $MSG) {echo "send a message to the client: {$client_id} | {$MSG [' action '] [' name ']} |". The date (' Y -m - dH: I: s'). "\ r \ n"; $this->server->push($client_id, json_encode($msg)); } /** * close the client link * @param $client_id */ public function closeClient($client_id) {$this->server->close($client_id); } /** * Add timer * @param $client_id * @param $tick_time */ public function addTimer($client_id, $tick_time) {// Not implemented yet, use swoole native notation} /** ** to clear timer * @param $client_id * @param $arr */ public function clearTimer($client_id, &$arr) { if (is_array($arr)) { foreach ($arr[$client_id] as $val) { if (is_array($val)) { foreach ($val as $v) { swoole_timer_clear($v); } } else { swoole_timer_clear($val); } } } unset($arr[$client_id]); }}

html front-end javascript program

The $(document). Ready (function () {varwsurl = "ws: / / 182.92.101.206:9999 /"; console.log(wsurl); varwebsocket = new WebSocket(wsurl); Websocket. onopen= function(evt){console.log('Server: opens WebSocket connection '); }; Websocket. onclose= function(evt){console.log('Server: close WebSocket connection '); }; websocket.onmessage= function(evt){ varres = JSON.parse(evt.data); console.log('Server: received message (from: '+res+' request)'); console.log(res); }; websocket.οnerrοr= function(evt){console.log('Server: error '); console.log(evt.data); } functiondoSend(msg){console.log('Client: send message '+ msg); websocket.send(msg); }});

start the start.php file

start the start.php file, cd to the specified directory, and then run PHP start.php on the php-CLI. This way thread protection is not enabled and the thread is still occupied after the program is shut down.

require'src/WebSocketSwoole/WebSocketService.php';
// require './WebSocketService.php';
session_start();
// $demoService = new\WebSocketSwoole\WebSocketService();
$demoService =\WebSocketSwoole\WebSocketService::getInstance();
$demoService->run();

Sum up

To this article about the method of building swoole php message push under Linux is introduced to this, more related swoole php message push content please search the previous articles of the script home or continue to browse the following related articles hope that you will support the script home in the future!

Related article

  • php的declare控制符和ticks教程(附示例)

    php declare controller and ticks tutorial (with examples)

    declare is the process control structure of PHP, directive currently supports two directives, the use of ticks needs to be combined with register_tick_function, see the following small example
    2014-03-03
  • PHP上传文件参考配置大文件上传

    PHP File upload Refer to Configure large file upload

    This article introduces the relevant knowledge of php upload file reference configuration large file upload, involving the relevant knowledge of php upload file configuration, interested friends learn it together
    2015-12-12
  • PHP学习之预定义变量(实例讲解)

    Predefined variables for PHP Learning (Examples)

    The following Xiaobian will share a PHP learning of predefined variables (example explanation), with a good reference value, I hope to help you. Let's take a look
    2018-01-01
  • php使用curl模拟浏览器表单上传文件或者图片的方法

    php uses curl to simulate the way a browser form uploads a file or image

    This article mainly introduces php using curl to simulate the browser form upload a file or picture method, Xiaobian feel very good, now share to you, also give you a reference. Let's take a look
    2018-11-11
  • 纯真IP数据库的应用 IP地址转化成十进制

    The application IP address of the pure IP database is converted to decimal

    Because the IP data in the pure database is different from the ordinary IP, it can be compared after transformation
    2009-06-06
  • 初识PHP中的Swoole

    Get to know Swoole in PHP

    Swoole is a PHP advanced Web development framework, the framework is not to improve the performance of the website, is to improve the efficiency of website development. Minimum performance loss for maximum development efficiency
    2016-04-04
  • php车辆违章查询数据示例

    php Vehicle violation query data example

    The national vehicle violation data interface has supported about 300 urban violation inquiries and has connected tens of thousands of apps. This article introduces php vehicle violation query data example, you can have a look at the need for friends.
    2016-10-10
  • Yii框架表单模型和验证用法

    Yii framework form model and validation usage

    This article mainly introduces the Yii framework form model and verification usage, combined with examples to analyze the principle of Yii form model and the use of the verifier skills, need friends can refer to
    2016-05-05
  • PHP魔术方法的使用示例

    PHP magic method use example

    This article mainly introduces the use of PHP magic method examples, this article explains the use of __get, __set, __call, __callStatic, __toString, __invoke and other magic methods, need friends can refer to
    2015-06-06
  • 注意!PHP 7中不要做的10件事

    Attention! 10 Things not to do in PHP 7

    This article mainly introduces in detail the 10 things not to do in PHP 7, has a certain reference value, interested partners can refer to it
    2016-09-09

Latest comments