<?php
/**
* ws優化 + task機制 + 毫秒定時器
*/
class Ws
{
CONST HOST = "0.0.0.0";
CONST PORT = 8812;
public $ws = null;
public function __construct()
{
$this->ws = new swoole_websocket_server("0.0.0.0", 8812);
$this->ws->set([
'worker_num' => 2,
'task_worker_num' => 2,
]);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
/**
* 監聽ws連接事件
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:23:40+0800
* @param [type] $ws [description]
* @param [type] $request [description]
* @return [type] [description]
*/
public function onOpen($ws, $request)
{
var_dump($request->fd);
// 定時器 將客戶端標識爲1的每兩秒執行一次
if ($request->fd == 1) {
swoole_timer_tick(2000, function($timer_id) {
echo "兩秒執行的結果 定時器id爲:{$timer_id}\n";
});
}
}
/**
* 監聽ws消息事件
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:25:25+0800
* @param [type] $ws [description]
* @param [type] $frame [description]
* @return [type] [description]
*/
public function onMessage($ws, $frame)
{
echo "服務端監聽到客戶端的消息:{$frame->data}\n";
// 此處假設10s執行代碼 使用task 做個投遞任務
$data = [
'task' => 1,
'fd' => $frame->fd,
];
// $ws->task($data); // 執行到此處task不會阻塞 會直接執行push
swoole_timer_after(5000, function() use($ws, $frame) {
echo "服務端監聽到客戶端的消息5秒之後 想客戶端發送的定時器信息\n";
$ws->push($frame->fd, '5秒之後執行定時器');
}); // 異步定時器 執行到此處task不會阻塞 會直接執行push(↓↓↓↓)
$ws->push($frame->fd, "服務端返回給客戶端數據:" . date('Y-m-d H:i:s', time()));
}
public function onTask($serv, $tash_id, $worker_id, $data)
{
print_r($data);
// 假設場景耗時10s
sleep(10);
return "on task finish";// 告訴worker
}
// 此處的$data爲 ’on task finish‘
public function onFinish($serv, $taskId, $data)
{
echo "taskId:{$taskId}\n";
echo "task結果接收成功:{$data}";
}
/**
*
* @Author Jartin
* @Url string
* @DateTime 2020-03-22T19:28:44+0800
* @param [type] $ws [description]
* @param [type] $fd [description]
* @return [type] [description]
*/
public function onClose($ws, $fd)
{
echo "客戶端ID:{$fd}\n";
}
}
$obj = new Ws();