帶定時器的ws服務
阿新 • • 發佈:2018-12-14
客戶端連結後: 每隔2s詢問客戶是否線上 客戶端傳送訊息5s後 給出一個回饋
<?php /* 常規定時器: crontab swoole定時器 swoole_timer_tick swoole_timer_after */ $server = new swoole_websocket_server("0.0.0.0",8812); //監聽websocket連線開啟事件 $server->on('open','onOpen'); function onOpen($server,$request){ print_r($request->fd); swoole_timer_tick(2000,function($time_id)use($server,$request){ // echo "2s:timerId:{$time_id}\n";i $server->push($request->fd,$time_id."ask:Are you Onlie?"); }); } /* $server->on('open', function (swoole_websocket_server $server, $request) { echo "server: handshake success with fd{$request->fd}\n"; }); */ //訊息事件 $server->on('message', function (swoole_websocket_server $server, $frame) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n"; $server->push($frame->fd, "this is server sucess:".$frame->data);//把資料push到客戶端 推送資料 swoole_timer_after(5000,function()use($server,$frame){ echo "5s-after\n"; $server->push($frame->fd,"server-time\n"); }); }); //客戶端關閉事件 $server->on('close', function ($ser, $fd) { echo "client {$fd} closed\n"; }); $server->start();