swoft-cloud / swoft

🚀 PHP Microservice Full Coroutine Framework
https://swoft.org
Apache License 2.0
5.58k stars 786 forks source link

在http接口里面使用websocket推送消息,app/bean.php里面配置了http响应 #1412

Open puj798 opened 3 years ago

puj798 commented 3 years ago
/**
     * @RequestMapping("/hi")
     * @return Response
     */
    public function hi():Response
    {

          server()->push(7, 'http响应');

    }

//运行出现Call to undefined method Swoft\Http\Server\HttpServer::push()这个错误

guoguicheng commented 3 years ago

我也有一样的需求,出现了同样的问题,没法在httpServer里面使用wsServer,有什么解决办法了嘛?

inhere commented 3 years ago

这个要反过来配置,在ws server里启用 http 就可以了。

guoguicheng commented 3 years ago

我在MasterStartListener内判断启动进程为WebSocket时,使用sgo创建一个携程,通过轮询redis,有数据就使用Task发送消息,问题已经解决

public function handle(EventInterface $event): void
{
    /** @var HttpServer $httpServer */
    $httpServer = $event->getTarget();
    $serverType = $httpServer->getServerType();
    if ('WebSocket' === $serverType) {
        sgo(function () {
            Redis::call(function ($redis) {
                while (1) {
                    $data = $redis->rPop('massage');
                    Task::async('msgTask', 'send', [...]);
                }
            });
        });
    }
}