class WS{
//构建一个构造函数
CONST HOST ="192.168.33.10";
CONST PORT =9504;
public $ws = null;
public function __construct()
{
$this->ws = new swoole_websocket_server(self::HOST,self::PORT);
/*$this->ws->set([
'worker_num' => 8,
'task_worker_num' => 8,
]);*/
$this->ws->set([
'worker_num' => 8,
'task_worker_num' => 8,
'enable_static_handler' => true,
'document_root' => "/vagrant_data/web/singwa",//设置根目录这里根据你自己的路径来写
]);
//监听事件的打开
$this->ws->on('open',[$this,'onOpen']);
//onTask
$this->ws->on('task',[$this,'onMessage']);
//onFinish 事件
$this->ws->on('finish',[$this,'onFinish']);
//监听消息事件
$this->ws->on('message',[$this,'onMessage']);
//监听关闭事件
$this->ws->on('close',[$this,'onClose']);
$this->ws->start();
}
//打开事件
public function onOpen($ws,$request){
echo "open connetc {$request->fd}\n";
}
//监听消息事件方法:
public function onMessage($ws,$frame){
//echo "Receive:".$frame->fd."返回数据信息:".$frame->data."opcode {$frame->opcode}:fin:{$frame->finish}\n";
echo "返回数据信息:".$frame->data."opcode {$frame->opcode}:fin:{$frame->finish}\n";
$data = [
'task' => 1,
'fd' => $frame->fd,
];
$ws->task($data); //需要接收一个投递任务
$ws->push($frame->fd,"return connect success返回客户端数据信息6{$frame->data}"); //发送给客户端信息
}
//onTask()事件
public function onTask($serv,$task_id, $worker_id, $data){
// print ($data."task_id{$task_id}\n");
print ($data);
//耗时场景 10s
sleep(10);
return "on finish work"; //告诉WORKER 请求onFinish方法
}
public function onFinish($serv,$task_id,$data){
echo "onFinish:{$task_id}\n";
print ("得到的数据是:".$data); //这里的$data 是 onTask 方法 返回 的信息即 return "on finish work"; 值
}
//监听关闭事件
public function onClose($ws,$fd){
echo "close:{$fd}client\n";
}
}
$WS = new WS();