您当前的位置: 首页 >  websocket

Swoole-WebSocket毫秒定时器

发布时间:2021-08-11 16:08:26 ,浏览量:6

Swoole毫秒定时器
  • 简介
  • 别名
  • 应用
    • Ws.php
    • index.html
简介

常规定时器:linux crontab

Swoole定时器 swoole_timer_tick swoole_timer_after

别名

tick()、after()、clear() 都拥有一个函数风格的别名

类静态方法 函数风格别名 Swoole\Timer::tick() swoole_timer_tick() Swoole\Timer::after() swoole_timer_after() Swoole\Timer::clear() swoole_timer_clear() 应用 Ws.php
 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 进程数。【默认值:CPU 核数】 'worker_num'=>2, # 配置 Task 进程的数量 '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连接事件 public function onOpen($ws,$request) { var_dump($request->fd); if($request->fd==1) { /*
       tick() 别名函数 swoole_timer_tick
       设置一个间隔时钟定时器。

       与 after 定时器不同的是 tick 定时器会持续触发,直到调用 Timer::clear 清除。
       */ //每2秒执行 swoole_timer_tick(2000,function($timer_id){ echo "2s:timerId:{$timer_id}\n"; }); } } # 监听ws消息事件 public function onMessage($ws,$frame) { echo "接收前端发来的信息:{$frame->data}\n"; // todo 10s $data = [ 'task'=>1, 'fd'=>$frame->fd, ]; /*
    after()
    在指定的时间后执行函数。Swoole\Timer::after 函数是一个一次性定时器,执行完成后就会销毁。

    此函数与 PHP 标准库提供的 sleep 函数不同,after 是非阻塞的。而 sleep 调用后会导致当前的进程进入阻塞,将无法处理新的请求。
     */ swoole_timer_after(5000,function() use($ws,$frame) { echo "5s-after\n"; $ws->push($frame->fd,"5秒后发送给前台的消息:".date("Y-m-d H:i:s")); }); $ws->push($frame->fd,"发送给前台的消息:".date("Y-m-d H:i:s")); } public function onTask($serv,$taskId,$workerId,$data){ print_r($data); //耗时场景 sleep(10); return "on task finish";//告诉work } public function onFinish($serv,$taskId,$data){ echo "taskId:{$taskId}\n"; echo "执行完成的异步:{$data}\n"; } # close public function onClose($ws,$fd){ echo "client:{$fd}\n"; } } $obj=new Ws(); 

运行服务 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

在这里插入图片描述

index.html
 websocket.send("发送 hello-willem"); console.log("conected-swoole-success"); } //实例化 onmessage websocket.onmessage=function(evt){ alert(evt.data+":接收到后端发来的信息弹窗"); console.log("ws-server-return-data:"+evt.data); } //onclose websocket.onclose=function(evt){ console.log("close"); } //onerror websocket.onerror=function(evt,e){ console.log("error:"+evt.data); }             
关注
打赏
1688896170
查看更多评论

暂无认证

  • 6浏览

    0关注

    108697博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0502s