Home > Article > PHP Framework > A brief discussion on the usage of worker class in workererman
This 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"
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/
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 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
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
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 即可
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>
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 a88b79ba1ccee8890e978c768d80530d://597b86729050bec83322e701454c0933
9c7ca7865317bfd18b12544ef4ebea19 can be in the following format:
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
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
当前worker进程的id编号,范围为0到$worker->count-1。进程重启后id编号值是不变的。
name
设置当前Worker实例的名称,方便运行status命令时识别进程。不设置时默认为none。
protocol
设置当前Worker实例的协议类。
transport
设置当前Worker实例所使用的传输层协议,目前只支持3种(tcp、udp、ssl)。不设置默认为tcp。
daemonize
此属性为全局静态属性,表示是否以daemon(守护进程)方式运行。如果启动命令使用了 -d参数,则该属性会自动设置为true。也可以代码中手动设置。
logFile
用来指定workerman日志文件位置。此文件记录了workerman自身相关的日志,包括启动、停止等。
Worker::$logFile = '/tmp/workerman.log’;
stdoutFile
此属性为全局静态属性,如果以守护进程方式(-d启动)运行,则所有向终端的输出(echo var_dump等)都会被重定向到stdoutFile指定的文件中。
Worker::$stdoutFile = 'test.log’;
pidFile
如果无特殊需要,建议不要设置此属性
Worker::$pidFile = '/var/run/workerman.pid’;
user
设置当前Worker实例以哪个用户运行。此属性只有当前用户为root时才能生效。不设置时默认以当前用户运行。
建议$user设置权限较低的用户,例如www-data、apache、nobody等。
connections
array(id=>connection, id=>connection, ...)
此属性中存储了当前进程的所有的客户端连接对象,其中id为connection的id编号
reloadable
设置当前Worker实例是否可以reload,即收到reload信号后是否退出重启。不设置默认为true,收到reload信号后自动重启进程。
reusePort
设置当前worker是否开启监听端口复用(socket的SO_REUSEPORT选项),默认为false,不开启。
globalEvent
此属性为全局静态属性,为全局的eventloop实例,可以向其注册文件描述符的读写事件或者信号事件。
设置Worker子进程启动时的回调函数,每个子进程启动时都会执行。
回掉函数参数 $worker Worker 对象
$worker->onWorkerStart = function($worker){ //代码 }; $worker->onWorkerStart = 'test’; function test($worker){ echo 'hhhhh'; }
onConnect
当客户端与Workerman建立连接时(TCP三次握手完成后)触发的回调函数。每个连接只会触发一次onConnect回调。
回调函数的参数
$connection
连接对象,即TcpConnection实例,用于操作客户端连接,如发送数据,关闭连接等
$worker->onConnect = function($connection){ echo 'new connect....'.$connection->getRemoteIp(); };
onMessage
当客户端通过连接发来数据时(Workerman收到数据时)触发的回调函数
回调函数的参数
$connection
连接对象,即TcpConnection实例,用于操作客户端连接,如发送数据,关闭连接等
$data
客户端连接上发来的数据,如果Worker指定了协议,则$data是对应协议decode(解码)了的数据
$worker->onMessage = function($connection,$data){ echo $data; $connection->send('hello '.$data.PHP_EOL); };
onClose
当客户端连接与Workerman断开时触发的回调函数。不管连接是如何断开的,只要断开就会触发onClose。每个连接只会触发一次onClose。由于断网或者断电等极端情况断开的连接 ,也就无法及时触发onClose,这种情况需要通过应用层心跳来解决
$worker->onClose = function($connection){ echo 'connection close'; };
onError
当客户端的连接上发生错误时触发。
目前错误类型有
1、调用Connection::send由于客户端连接断开导致的失败(紧接着会触发onClose回调) (code:WORKERMAN_SEND_FAIL msg:client closed)
2、在触发onBufferFull后(发送缓冲区已满),仍然调用Connection::send,并且发送缓冲区仍然是满的状态导致发送失败(不会触发onClose回调)(code:WORKERMAN_SEND_FAIL msg:send buffer full and drop package)
3、使用AsyncTcpConnection异步连接失败时(紧接着会触发onClose回调) (code:WORKERMAN_CONNECT_FAIL msg:stream_socket_client返回的错误消息)
onWorkerReload
此特性不常用到。
设置Worker收到reload信号后执行的回调。
可以利用onWorkerReload回调做很多事情,例如在不需要重启进程的情况下重新加载业务配置文件。
onBufferFull
每个连接都有一个单独的应用层发送缓冲区,如果客户端接收速度小于服务端发送速度,数据会在应用层缓冲区暂存,如果缓冲区满则会触发onBufferFull回调。
缓冲区大为TcpConnection::$maxSendBufferSize,默认值为1MB,可以为当前连接动态设置缓冲区大小例
onBufferDrain
每个连接都有一个单独的应用层发送缓冲区,缓冲区大小由TcpConnection::$maxSendBufferSize决定,默认值为1MB,可以手动设置更改大小,更改后会对所有连接生效。
runAll
运行所有Worker实例。
Worker::runAll()执行后将永久阻塞,也就是说位于Worker::runAll()后面的代码将不会被执行。所有Worker实例化应该都在Worker::runAll()前进行。
stopAll
停止当前进程(子进程)的所有Worker实例并退出。
此方法用于安全退出当前子进程,作用相当于调用exit/die退出当前子进程。
listen
用于实例化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(); //主进程监控各个worker的状态 }
SAPI(Server Application Programming Interface)服务器应用程序编程接口,即PHP与其他应用交互的接口,PHP脚本要执行有很多方式,通过Web服务器,或者直接在命令行下,也可以嵌入在其他程序中。
常见的SAPI有:cgi、fast-cgi、cli、apache模块的DLL、isapi
01 SIGHUP 挂起(hangup)
02 SIGINT 中断,当用户从键盘按^c键或^break键时
03 SIGQUIT 退出,当用户从键盘按quit键时
04 SIGILL 非法指令
05 SIGTRAP 跟踪陷阱(trace trap),启动进程,跟踪代码的执行
06 SIGIOT IOT指令
07 SIGEMT EMT指令
08 SIGFPE 浮点运算溢出
09 SIGKILL 杀死、终止进程
10 SIGBUS 总线错误
11 SIGSEGV 段违例(segmentation violation),进程试图去访问其虚地址空间以外的位置
12 SIGSYS 系统调用中参数错,如系统调用号非法
13 SIGPIPE 向某个非读管道中写入数据
14 SIGALRM 闹钟。当某进程希望在某时间后接收信号时发此信号
15 SIGTERM 软件终止(software termination)
16 SIGUSR1 用户自定义信号1
17 SIGUSR2 用户自定义信号2
18 SIGCLD 某个子进程死
更多计算机编程相关知识,请访问:编程视频!!
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!