A brief discussion on the usage of worker class in workererman
Feb 03, 2021 am 11:01 AMThis article will introduce you to workerman, and talk about the usage of the worker class in workerman. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related recommendations: "workerman Tutorial"
What is a workerman?
Workerman is an open source high-performance asynchronous PHP socket instant messaging framework. Supports high concurrency and ultra-high stability, and is widely used in mobile apps, mobile communications, WeChat applets, mobile game servers, online games, PHP chat rooms, hardware communications, smart homes, Internet of Vehicles, Internet of Things and other fields. development. Supports TCP long connections, supports Websocket, HTTP and other protocols, and supports custom protocols. It has many high-performance components such as asynchronous Mysql, asynchronous Redis, asynchronous Http, MQTT IoT client, asynchronous message queue, etc.
Official website: https://www.workerman.net/
workerman’s features
Pure PHP development
Support PHP multi-process
Support TCP, UDP
Support long connection
Support various application layer protocols
Support high concurrency
Support smooth service restart
Support HHVM
Support running child processes as specified users
Comes with monitoring
Support millisecond level timer
Support asynchronous IO
Support permanent retention of objects or resources
High performance
Support distributed deployment
Support heartbeat detection
workerman application scenario
workerman installation
Environmental requirements:
Workerman has been able to support both Linux and Windows systems since version 3.5.3.
Requires PHP>=5.3.3, and configure PHP environment variables.
Note: This tutorial uses Linux and does not talk about Windows. It is not recommended to use Windows system for actual use.
Linux lnmp one-click installation script
1. Install PHP>=5.3.3 , and installed pcntl and posix extensions --enable-pcntl --enable-posix
2. It is recommended to install event or libevent extension, but it is not necessary (note that event extension requires PHP>=5.4)
curl -Ss http://www.workerman.net/check.php | php
git clone https://github.com/walkor/Workerman
Install libevent
yum install libevent-devel
php version is below 7
wget http://pecl.php.net/get/libevent-0.1.0.tgz
Note that currently the libevent extension does not support php7, and php7 users can only use the Event extension.
wget http://pecl.php.net/get/event-2.4.3.tgz
Decompress Compile
/user/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
Configure to php.ini
workerman directory structure

workerman simple development demo
implement a simple http server
require_once 'workman/Autoloader.php'; use \Workerman\Worker; $http_work = new Worker('http://0.0.0.0:1111’); $http_work->onMessage = function($conn,$data){ $conn->send('hello workman'); }; Worker::runAll(); 瀏覽器 訪問 ip:1111 即可
implement websocket
ws.php
require_once 'workman/Autoloader.php'; use \Workerman\Worker; $http_work = new Worker('websocket://0.0.0.0:2222'); $http_work->onMessage = function($conn,$data){ $conn->send('hello workman'.$data); }; Worker::runAll(); <!DOCTYPE HTML> <html> <body> <script> ws = new WebSocket("ws://192.168.113.136:2222"); ws.onopen = function(){ ws.send('lampol'); } ws.onmessage = function(e){ console.log(e.data) } </script> </body> </html>
workermanPrinciple
Worker class
There are two important classes Worker and Connection in WorkerMan.
The Worker class is used to implement port monitoring, and can set callback functions for client connection events, connection message events, and connection disconnection events to implement business processing.
$worker = new Worker($listen,$context); //Instantiation Return object
The format of $listen is
tcp: For example, tcp://0.0.0.0:8686
udp: For example, udp://0.0.0.0 :8686
unix: For example, unix:///tmp/my_file (requires Workerman>=3.2.7)
http: For example, http://0.0.0.0:80
websocket: For example, websocket://0.0.0.0:8686
text: For example, text://0.0.0.0:8686 (text is Workerman’s built-in text protocol and is compatible with telnet. For details, see the Text protocol section in the appendix )
$context Context options for passing socket
Worker class attributes
count
Set how many current Worker instances are started process, defaults to 1 if not set.
This property must be set before Worker::runAll(); is run to be valid. Windows systems do not support this feature.
The basis for setting the number of processes:
1. Number of cpu cores
2. Memory size
3. Whether the business is IO-intensive or CPU-intensive
If you don’t know which type of business you prefer, you can set the number of processes to about twice the number of CPU cores.
lscpu top ? 1 Check the number of cpu cores
id
當(dāng)前worker進程的id編號,范圍為0到$worker->count-1。進程重啟后id編號值是不變的。
name
設(shè)置當(dāng)前Worker實例的名稱,方便運行status命令時識別進程。不設(shè)置時默認為none。
protocol
設(shè)置當(dāng)前Worker實例的協(xié)議類。
transport
設(shè)置當(dāng)前Worker實例所使用的傳輸層協(xié)議,目前只支持3種(tcp、udp、ssl)。不設(shè)置默認為tcp。
daemonize
此屬性為全局靜態(tài)屬性,表示是否以daemon(守護進程)方式運行。如果啟動命令使用了 -d參數(shù),則該屬性會自動設(shè)置為true。也可以代碼中手動設(shè)置。
logFile
用來指定workerman日志文件位置。此文件記錄了workerman自身相關(guān)的日志,包括啟動、停止等。
Worker::$logFile = '/tmp/workerman.log’;
stdoutFile
此屬性為全局靜態(tài)屬性,如果以守護進程方式(-d啟動)運行,則所有向終端的輸出(echo var_dump等)都會被重定向到stdoutFile指定的文件中。
Worker::$stdoutFile = 'test.log’;
pidFile
如果無特殊需要,建議不要設(shè)置此屬性
Worker::$pidFile = '/var/run/workerman.pid’;
user
設(shè)置當(dāng)前Worker實例以哪個用戶運行。此屬性只有當(dāng)前用戶為root時才能生效。不設(shè)置時默認以當(dāng)前用戶運行。
建議$user設(shè)置權(quán)限較低的用戶,例如www-data、apache、nobody等。
connections
array(id=>connection, id=>connection, ...)
此屬性中存儲了當(dāng)前進程的所有的客戶端連接對象,其中id為connection的id編號
reloadable
設(shè)置當(dāng)前Worker實例是否可以reload,即收到reload信號后是否退出重啟。不設(shè)置默認為true,收到reload信號后自動重啟進程。
reusePort
設(shè)置當(dāng)前worker是否開啟監(jiān)聽端口復(fù)用(socket的SO_REUSEPORT選項),默認為false,不開啟。
globalEvent
此屬性為全局靜態(tài)屬性,為全局的eventloop實例,可以向其注冊文件描述符的讀寫事件或者信號事件。
Worker類回調(diào)屬性
onWorkerStart
設(shè)置Worker子進程啟動時的回調(diào)函數(shù),每個子進程啟動時都會執(zhí)行。
回掉函數(shù)參數(shù) $worker Worker 對象
$worker->onWorkerStart = function($worker){ //代碼 }; $worker->onWorkerStart = 'test’; function test($worker){ echo 'hhhhh'; }
onConnect
當(dāng)客戶端與Workerman建立連接時(TCP三次握手完成后)觸發(fā)的回調(diào)函數(shù)。每個連接只會觸發(fā)一次onConnect回調(diào)。
回調(diào)函數(shù)的參數(shù)
$connection
連接對象,即TcpConnection實例,用于操作客戶端連接,如發(fā)送數(shù)據(jù),關(guān)閉連接等
$worker->onConnect = function($connection){ echo 'new connect....'.$connection->getRemoteIp(); };
onMessage
當(dāng)客戶端通過連接發(fā)來數(shù)據(jù)時(Workerman收到數(shù)據(jù)時)觸發(fā)的回調(diào)函數(shù)
回調(diào)函數(shù)的參數(shù)
$connection
連接對象,即TcpConnection實例,用于操作客戶端連接,如發(fā)送數(shù)據(jù),關(guān)閉連接等
$data
客戶端連接上發(fā)來的數(shù)據(jù),如果Worker指定了協(xié)議,則$data是對應(yīng)協(xié)議decode(解碼)了的數(shù)據(jù)
$worker->onMessage = function($connection,$data){ echo $data; $connection->send('hello '.$data.PHP_EOL); };
onClose
當(dāng)客戶端連接與Workerman斷開時觸發(fā)的回調(diào)函數(shù)。不管連接是如何斷開的,只要斷開就會觸發(fā)onClose。每個連接只會觸發(fā)一次onClose。由于斷網(wǎng)或者斷電等極端情況斷開的連接 ,也就無法及時觸發(fā)onClose,這種情況需要通過應(yīng)用層心跳來解決
$worker->onClose = function($connection){ echo 'connection close'; };
onError
當(dāng)客戶端的連接上發(fā)生錯誤時觸發(fā)。
目前錯誤類型有
1、調(diào)用Connection::send由于客戶端連接斷開導(dǎo)致的失?。ňo接著會觸發(fā)onClose回調(diào)) (code:WORKERMAN_SEND_FAIL msg:client closed)
2、在觸發(fā)onBufferFull后(發(fā)送緩沖區(qū)已滿),仍然調(diào)用Connection::send,并且發(fā)送緩沖區(qū)仍然是滿的狀態(tài)導(dǎo)致發(fā)送失敗(不會觸發(fā)onClose回調(diào))(code:WORKERMAN_SEND_FAIL msg:send buffer full and drop package)
3、使用AsyncTcpConnection異步連接失敗時(緊接著會觸發(fā)onClose回調(diào)) (code:WORKERMAN_CONNECT_FAIL msg:stream_socket_client返回的錯誤消息)
onWorkerReload
此特性不常用到。
設(shè)置Worker收到reload信號后執(zhí)行的回調(diào)。
可以利用onWorkerReload回調(diào)做很多事情,例如在不需要重啟進程的情況下重新加載業(yè)務(wù)配置文件。
onBufferFull
每個連接都有一個單獨的應(yīng)用層發(fā)送緩沖區(qū),如果客戶端接收速度小于服務(wù)端發(fā)送速度,數(shù)據(jù)會在應(yīng)用層緩沖區(qū)暫存,如果緩沖區(qū)滿則會觸發(fā)onBufferFull回調(diào)。
緩沖區(qū)大為TcpConnection::$maxSendBufferSize,默認值為1MB,可以為當(dāng)前連接動態(tài)設(shè)置緩沖區(qū)大小例
onBufferDrain
每個連接都有一個單獨的應(yīng)用層發(fā)送緩沖區(qū),緩沖區(qū)大小由TcpConnection::$maxSendBufferSize決定,默認值為1MB,可以手動設(shè)置更改大小,更改后會對所有連接生效。
Worker類接口方法
runAll
運行所有Worker實例。
Worker::runAll()執(zhí)行后將永久阻塞,也就是說位于Worker::runAll()后面的代碼將不會被執(zhí)行。所有Worker實例化應(yīng)該都在Worker::runAll()前進行。
stopAll
停止當(dāng)前進程(子進程)的所有Worker實例并退出。
此方法用于安全退出當(dāng)前子進程,作用相當(dāng)于調(diào)用exit/die退出當(dāng)前子進程。
listen
用于實例化Worker后執(zhí)行監(jiān)聽。
Worker類代碼流程分析
public function __construct($socket_name = '', $context_option = array()) public static function runAll() { static::checkSapiEnv(); //檢測命令行模式 static::init(); //初始化日志 pid workid… static::lock(); //啟動文件 加鎖 獨占鎖 static::parseCommand(); //解析命令 start stop restart … static::daemonize(); //守護進程運行 static::initWorkers(); //初始化 所有worker 實例 static::installSignal(); //安裝信號 static::saveMasterPid(); //保存主進程id static::unlock(); //解鎖 static::displayUI(); //展示UI static::forkWorkers(); //fork 進程 static::resetStd(); //重置輸入輸出 static::monitorWorkers(); //主進程監(jiān)控各個worker的狀態(tài) }
SAPI(Server Application Programming Interface)服務(wù)器應(yīng)用程序編程接口,即PHP與其他應(yīng)用交互的接口,PHP腳本要執(zhí)行有很多方式,通過Web服務(wù)器,或者直接在命令行下,也可以嵌入在其他程序中。
常見的SAPI有:cgi、fast-cgi、cli、apache模塊的DLL、isapi
Linux 常用SIG信號及其鍵值
01 SIGHUP 掛起(hangup)
02 SIGINT 中斷,當(dāng)用戶從鍵盤按^c鍵或^break鍵時
03 SIGQUIT 退出,當(dāng)用戶從鍵盤按quit鍵時
04 SIGILL 非法指令
05 SIGTRAP 跟蹤陷阱(trace trap),啟動進程,跟蹤代碼的執(zhí)行
06 SIGIOT IOT指令
07 SIGEMT EMT指令
08 SIGFPE 浮點運算溢出
09 SIGKILL 殺死、終止進程
10 SIGBUS 總線錯誤
11 SIGSEGV 段違例(segmentation? violation),進程試圖去訪問其虛地址空間以外的位置
12 SIGSYS 系統(tǒng)調(diào)用中參數(shù)錯,如系統(tǒng)調(diào)用號非法
13 SIGPIPE 向某個非讀管道中寫入數(shù)據(jù)
14 SIGALRM 鬧鐘。當(dāng)某進程希望在某時間后接收信號時發(fā)此信號
15 SIGTERM 軟件終止(software? termination)
16 SIGUSR1 用戶自定義信號1
17 SIGUSR2 用戶自定義信號2
18 SIGCLD 某個子進程死
更多計算機編程相關(guān)知識,請訪問:編程視頻!!
The above is the detailed content of A brief discussion on the usage of worker class in workererman. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

Introduction to how to implement the basic usage of Workerman documents: Workerman is a high-performance PHP development framework that can help developers easily build high-concurrency network applications. This article will introduce the basic usage of Workerman, including installation and configuration, creating services and listening ports, handling client requests, etc. And give corresponding code examples. 1. Install and configure Workerman. Enter the following command on the command line to install Workerman: c

How to implement the timer function in the Workerman document Workerman is a powerful PHP asynchronous network communication framework that provides a wealth of functions, including the timer function. Use timers to execute code within specified time intervals, which is very suitable for application scenarios such as scheduled tasks and polling. Next, I will introduce in detail how to implement the timer function in Workerman and provide specific code examples. Step 1: Install Workerman First, we need to install Worker

How to implement the reverse proxy function in the Workerman document requires specific code examples. Introduction: Workerman is a high-performance PHP multi-process network communication framework that provides rich functions and powerful performance and is widely used in Web real-time communication and long connections. Service scenarios. Among them, Workerman also supports the reverse proxy function, which can realize load balancing and static resource caching when the server provides external services. This article will introduce how to use Workerman to implement the reverse proxy function.

Workerman development: real-time video call based on UDP protocol Summary: This article will introduce how to use the Workerman framework to implement real-time video call function based on UDP protocol. We will have an in-depth understanding of the characteristics of the UDP protocol and show how to build a simple but complete real-time video call application through code examples. Introduction: In network communication, real-time video calling is a very important function. The traditional TCP protocol may have problems such as transmission delays when implementing high-real-time video calls. And UDP

How to use Workerman to build a high-availability load balancing system requires specific code examples. In the field of modern technology, with the rapid development of the Internet, more and more websites and applications need to handle a large number of concurrent requests. In order to achieve high availability and high performance, the load balancing system has become one of the essential components. This article will introduce how to use the PHP open source framework Workerman to build a high-availability load balancing system and provide specific code examples. 1. Introduction to Workerman Worke

Workerman is a high-performance asynchronous event-driven framework developed based on PHP. It can easily realize the development of long connections under the TCP/UDP protocol. In addition, Workerman also provides the function of realizing file transfer, which can be used in scenarios such as large file transfer and data backup. This article will introduce how to implement the file transfer function in Workerman and provide specific code examples. 1. File upload function To implement the file upload function, the client needs to send the file to be uploaded to the server, and the server verifies
