您好,登錄后才能下訂單哦!
server:
class Server
{
private $_serv = null;
private $_workers = [];
private $_worker_num = 2;
public function __construct()
{
$this->_serv = new swoole_server('127.0.0.1', 9501);
$this->_serv->on('start', array($this, 'onStart'));
$this->_serv->on('workerstart', array($this, 'onWorkerStart'));
$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 onStart($serv)
{
echo "start \n";
}
public function onWorkerStart($serv, $worker_id)
{
echo "worker start\n";
}
public function onConnect($serv, $fd, $from_id )
{
echo "connect..\n";
}
public function onReceive(swoole_server $serv, $fd, $from_id, $data)
{
for ($i = 0; $i < $this->_worker_num ;$i++) {
$process = new swoole_process(array($this, 'onProcess'), false, false);
$process->useQueue();
$pid = $process->start();
echo $pid;
$this->_workers[$pid] = $process;
}
foreach ($this->_workers as $pid => $worker) {
echo $process->push("hello worker[{$pid}]\n");
sleep(2);//停2秒,不然主進程pop時 獲取消息太快,而阻塞狀態了,push完給子進程消息,子進程邏輯還沒處理完
//(1)不加這停兩秒時,可能主進程馬上pop時,隊列是空的,主進程阻塞狀態了,下面子進程只能pop和push一次,再pop時也阻塞狀態了
//客戶端再發send消息時,服務器不響應,除非新client進來,發send,主進程阻塞取消了,第一個客戶端又可以發send消息了,第二個客戶端
//發send消息時,服務端不響應,這種情況發生了
$result = $process->pop();//默認模式下,如果隊列中沒有數據,pop方法會阻塞等待
echo "From worker: $result\n";//這里主進程,接受到的子進程的數據
}
for($i = 0; $i < $this->_worker_num; $i++)
{
$ret = swoole_process::wait();
$pid = $ret['pid'];
unset($this->_workers[$pid]);
echo "Worker Exit, PID=".$pid.PHP_EOL;
}
}
public function onProcess($worker)
{
$msg_status = $worker->statQueue();
if($msg_status['queue_num'] > 0)
{
$recv = $worker->pop();
echo "FROM master {$recv}\n";
$worker->push("heheh parent");//子進程處理完邏輯,不是馬上push數據給主進程 sleep(2)
}
$worker->exit(0);
}
public function onClose($serv, $fd, $from_id)
{
echo "close.\n";
}
}
new Server();
client:
$cli = new Swoole_client(SWOOLE_SOCK_TCP);
$cli->connect('127.0.0.1', 9501, 1);
fwrite(STDOUT, '輸入消息:');
$msg = trim(fgets(STDIN));
echo $cli->send($msg);
echo $cli->recv()."\n";
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。