<慧脱?php
swoole = new swoole_server("0.0.0.0",9503);
? ? ? ? $this->swoole->set($this->config());
? ? ? ? $this->swooleInit();
? ? ? ? $this->swoole->start();
? ? }
? ? /**
? ? * swoole配置
? ? */
? ? public function config()
? ? {
? ? ? ? $config = [
? ? ? ? ? ? ? ? ? ? 'reactor_num'=>1, //默認(rèn)設(shè)置為CPU核數(shù),調(diào)節(jié)poll線程的數(shù)量饱亮,以充分利用多核,reactor_num必須小于或等于worker_num
? ? ? ? ? ? ? ? ? ? 'daemonize'=>true,//轉(zhuǎn)入后臺(tái)作為守護(hù)進(jìn)程運(yùn)行
? ? ? ? ? ? ? ? ? ? 'worker_num'=>2, //設(shè)置啟動(dòng)的worker進(jìn)程數(shù)量,類似于php-fpm的個(gè)數(shù),每個(gè)進(jìn)程占用40M內(nèi)存
? ? ? ? ? ? ? ? ? ? 'max_request'=>1000, //單個(gè)線程最大請(qǐng)求數(shù)
? ? ? ? ? ? ? ? ? ? 'max_conn'=>1000, //最多維持1000個(gè)tcp鏈接
? ? ? ? ? ? ? ? ? ? 'dispatch_mode'=>3, //worker進(jìn)程數(shù)據(jù)包分配模式1平均分配,2按FD取模固定分配赞咙,3搶占式分配普监,默認(rèn)為取模(dispatch=2)
? ? ? ? ? ? ? ? ? ? // 'task_worker_num'=>1, //務(wù)必要注冊(cè)onTask贵试、onFinish2個(gè)事件回調(diào)函數(shù),也是數(shù)據(jù)庫(kù)連接池的保證
? ? ? ? ? ? ? ? ? ? 'open_eof_check'=>true,
? ? ? ? ? ? ? ? ? ? 'package_eof'=>PHP_EOL,
? ? ? ? ? ? ? ? ? ? 'open_eof_split'=>true
? ? ? ? ? ? ? ? ? ? // 'log_file'=>'/log',
? ? ? ? ? ? ? ? ];
? ? ? ? return $config;
? ? }
? ? public function swooleInit()
? ? {
? ? ? ? $this->swoole->on("start",array($this,"onStart"));
? ? ? ? $this->swoole->on("connect",array($this,"onConnect"));
? ? ? ? $this->swoole->on("receive",array($this,"onReceive"));
? ? ? ? $this->swoole->on("connect",array($this,"onConnect"));
? ? ? ? $this->swoole->on("close",array($this,"onClose"));
? ? }
? ? public function onStart($server)
? ? {
? ? ? ? echo 'hello';
? ? }
? ? public function onConnect($server,$reactor_id)
? ? {
? ? ? ? echo 'world';?
? ? }
? ? public function onReceive($server,$fd,$reactor_id ,$data)
? ? {
? ? ? ? //這里創(chuàng)建進(jìn)程
? ? ? ? for($i = 0; $i< $this->worker_nums; $i++)
? ? ? ? {
? ? ? ? ? ? $process = new swoole_process(array($this,'onProcess'),false,false);
? ? ? ? ? ? $process->useQueue();
? ? ? ? ? ? $pid = $process->start();
? ? ? ? ? ? $this->workers[$pid] = $process;
? ? ? ? }
? ? ? ? //循環(huán)隊(duì)列
? ? ? ? foreach ($this->workers as $pid=>$worker)
? ? ? ? {
? ? ? ? ? ? $process->push("hello{$pid}");
? ? ? ? ? ? $result = $process->pop();
? ? ? ? ? ? echo "From worker: $result\n";//這里主進(jìn)程,接受到的子進(jìn)程的數(shù)據(jù)
? ? ? ? }
? ? ? ? //釋放
? ? ? ? for($i=0; $i < $this->worker_nums; $i++)
? ? ? ? {
? ? ? ? ? ? $ret = swoole_process::wait();
? ? ? ? ? ? $pid = $ret['pid'];
? ? ? ? ? ? unset($this->worker_nums[$pid]);
? ? ? ? ? ? echo "Worker Exit, PID=".$pid.PHP_EOL;
? ? ? ? }
? ? }
? ? public function onProcess($worker)
? ? {
? ? ? ? $recv? = $worker->pop();
? ? ? ? echo "FROM master {$recv}\n";
? ? ? ? $worker->push("heheh parent");
? ? ? ? $worker->exit(0);
? ? }
? ? public function onClose($server,$fd,$reactor_id)
? ? {
? ? ? ? echo 'close';
? ? }
}
$server = new server();
?>