<?php //task任務要實現兩個方法onfinish ontask //還要設置worker_num date_default_timezone_set("PRC"); //設置爲本地時間 class taskserver { CONST host ="0.0.0.0"; CONST port =9502; public $sw = null; public function __construct() { $this->sw = new swoole_websocket_server(taskserver::host,taskserver::port); $this->sw->set([ 'worker_num'=>4, 'task_worker_num'=>4 ]); $this->sw->on('open',[$this,'onopen']); $this->sw->on('message',[$this,'onmessage']); $this->sw->on('task',[$this,'ontask']); $this->sw->on('finish',[$this,'onfinish']); $this->sw->on('close',[$this,'onclose']); $this->sw->start(); } public function onopen($serv,$request) { echo "來自{$request->fd}的鏈接已經創建\n"; echo "cpu數量:".SWOOLE_CPU_NUM()."\n"; } public function onmessage($serv,$frament) { echo "finish標識符---{$frament->finish}--opcode:{$frament->opcode}---fd:標識符{$frament->fd}\n"; //加入這裏有個耗費時間的操做 //這個數組沒什麼實際意義,只不過是模擬一個任務 $mytask=array([ "name"=>'陳培昌', 'age'=>22 ]); $serv->task($mytask);//把任務頭送進進程池,$mytask必須是可序列化的數據類型 $serv->push($frament->fd,"回饋來自客戶端{$frament->fd}的數據{$frament->data}---時間是".date("Y-m-d H:i:s")."\n"); } public function ontask($serv,$task_id,$worker_id,$mytask) { //這裏是真正執行阻塞任務的地方 //純屬無聊,打印看看是這個任務---也就是$mytask到底什麼貨色 print_r($mytask); //這段模擬阻塞/耗時操做 sleep(10); //返回處理結果 return "想去找小烤腸練巴西柔術"; } public function onfinish($serv,$task_id,$data) { echo "{$task_id}就緒,並返回結果----{$data}"; } public function onclose($serv,$fd) { echo "句柄:{$fd}關閉鏈接\n"; } } $cpc = new taskserver();
打印:php
來自1的鏈接已經創建
cpu數量:4
finish標識符---1--opcode:1---fd:標識符1
Array
(
[0] => Array
(
[name] => 陳培昌
[age] => 22
)web
)數組
--------------------------------10秒後又打印websocket
0就緒,並返回結果----想去找小烤腸練巴西柔術swoole