简介
添加一个用户自定义的工作进程。此函数通常用于创建一个特殊的工作进程,用于监控、上报或者其他特殊的任务。
https://wiki.swoole.com/wiki/page/390.html
Server
<?php
class Server
{
private $serv;
private $process;
private $testProcess;
public function __construct(){
$this->serv = new swoole_server('127.0.0.1', 9501);//注意这里要用多进程模式,不填写默认是多进程
$this->serv->set(array(
'worker_num' => 4,
'daemonize' => false,
'backlog' => 128,
));
$server = $this->serv;
$this->process = new swoole_process(function($process) use ($server) {
while (true) {//我猜测这里的一直循环,是不想浪费太多的资源,这里的资源暂时我还没有想到,想到后再更新。
print_r("进程1\n");
$msg = $process->read();//同步的,读取不到数据,就不往下执行.
foreach($server->connections as $conn) {
$server->send($conn, $msg);
}
}
});
$this->testProcess = new swoole_process(function($testProcess) use ($server){
while (true) {
print_r("进程2\n");
$msg = $testProcess->read();
foreach($server->connections as $conn) {
$server->send($conn, $msg);
}
}
});
$this->serv->addProcess($this->process);
$this->serv->addProcess($this->testProcess);
$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 onConnect(swoole_server $server, int $fd, int $reactorId){
print_r($fd."--连接上了\n");
}
public function onReceive(swoole_server $server, int $fd, int $reactor_id, string $data){
$this->process->write($data);
$this->testProcess->write("123");
print_r("主进程\n");
}
public function onClose(swoole_server $server, int $fd, int $reactorId){
print_r($fd."--关闭了连接\n");
}
}
new Server();
Client
<?php
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1))
{
exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("我是发送的数据\n");
while (true) {
$as = $client->recv();
print_r($as."\n");
}
执行结果
仔细看客户端的运行结果和服务端的输出结果。