yii2连接websocket服务实现服务端主动推送消息给客户端

上一篇写的是websocket的服务,这一篇写写调用服务和web端调用,接收消息部分

 1、调用websocket服务,主动推送消息的方法

$user_id,
                    'type'=>'WEBSOCKET_URL',
                    'msg' =>"您好,{$price}"
                ];
                $ws->send(json_encode($data,JSON_UNESCAPED_UNICODE));
                return "发送成功\n";
                usleep(100);
            } catch (BadOpcodeException $e) {
                throw new Exception($e->getMessage());
            }
            $ws->close();
        }
    }
}

2、在job中加入编写任务

user_id,$this->price);
            \Yii::$app->byfLog->channel('WebSocket')->info('推送消息给:'.$res);
        }catch (\Exception $exception){
            \Yii::$app->byfLog->channel('WebSocket')->error('推送消息错误'.$exception->getFile() . ':' . $exception->getLine() . ':' . $exception->getMessage() . PHP_EOL);
        }
    }
}

 3、推送消息加入异步队列:

getMessage());
        }
    }

    /**
     * Param: 推送消息任务加入队列
     * @param $user_id
     * @param $price
     * @return void
     * @throws Exception
     */
    public function actionSendMsgJob($user_id,$price)
    {
        try {
            //$this->user_id,$this->price
            \Yii::$app->queue->bind('websocket-job')->push(new SendMsgJob(['user_id' => $user_id,'price'=>$price]));
        } catch (BadOpcodeException $e) {
            throw new Exception($e->getMessage());
        }
    }

}

 手动推送消息任务队列测试的命令:

php yii web-socket-push/send-msg-job 112402 4.9999

4、web端连接websocket服务,实现接收消息




    
    websocket
    
    










5、配置supervisor

[program:websocket-job]
command=php yii queue/listen websocket-job
directory=/data/test.*********.cn/
autorestart=true
startsecs=3
startretries=3
stdout_logfile=log/websocket-job.out.log
stderr_logfile=log/websocket-job.err.log
stdout_logfile_maxbytes=2MB
stderr_logfile_maxbytes=2MB
user=111111
priority=999
numprocs=1
process_name=%(program_name)s_%(process_num)02d

你可能感兴趣的:(yii2,websocket,websocket)