12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace app\work\controller;
- use think\facade\Db;
- use think\worker\Server;
- use Workerman\Lib\Timer;
- use think\facade\View;
-
- /*
- * 业务需求示例:系统后台监听有新的商品订单,新消息等的通知,推送给所有登陆系统的用户。
- 逻辑:使用websocket建立连接,并设置定时器发送心跳保持连接不被断开。建立连接后,php端需要设置心跳时间,判断mysql业务表是否有新记录或者订单,如果有就推送消息给所有登陆系统用户,并更新该记录已推送。
- */
- class Push extends Server
- {
- protected $socket = 'http://0.0.0.0:2346'; //端口自行修改
-
- protected static $heartbeat_time = 55;
-
- public function onWorkerStart($worker)
- {
- //查看是否有新的充值或提现订单,有就推送给所有用户
- Timer::add(3, function () use ($worker) {
-
- $time_now = time();
-
-
- //是否有新消息
- $count = 10;
-
- if ($count > 0) {
-
-
-
- foreach ($worker->connections as $connection) {
- if (empty($connection->lastMessageTime)) {
- $connection->lastMessageTime = $time_now;
- }
-
- if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {
- //后台控制连接
- //前端断了 可以点击重新连接 类似游戏重新登录
- $connection->close();
- }
-
- $data = ['time'=> $time_now,'lastMessageTime' => $connection->lastMessageTime];
-
- $connection->send(json_encode($data));
- }
- //处理发送状态 ['is_push' => 1]
- } else {
- foreach ($worker->connections as $connection) {
- if (empty($connection->lastMessageTime)) {
- $connection->lastMessageTime = $time_now;
- continue;
- }
-
- if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) { //连接超时
- $connection->close();
- }
- }
- }
- });
- }
-
- /*
- * 客户端
- * http://workerman.dev.zx2049.com/work/push/index
- */
- public function index(){
-
- //获取规则
- $rule = ['默认规则'];
- for ($i = 1; $i <= 10; $i++) {
- $rule[] = '规则'.$i;
- }
- View::assign('rule',$rule);
- return View::fetch();
- }
-
- }
|