关于在控制器中使用SSE

南宫春水

问题描述

前端使用event-source-polyfill来SSE请求,因为需要携带token,后端在控制器中写了让如下方法。
其中$connection->getStatus()值都是:8。前端错误:
截图

<?php

namespace plugin\api\app\controller;

use plugin\api\app\model\UserModel;
use support\Db;
use support\Log;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;
use Workbunny\WebmanIpAttribution\Location;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\ServerSentEvents;
use Workerman\Timer;

class UserController extends Base
{
    protected $userModel = null;

    public function __construct()
    {
        $this->userModel = new UserModel();
    }

    /**
     * 获取用户苏哦有钱包余额
     * @param Request $request
     * @return Response
     * @throws \Webman\Push\PushException
     */
    public function getUserWalletBalance(Request $request)
    {
        $uid = JwtToken::getCurrentId();
        var_dump($request->header('accept'));
        // 使用SSE推送
        if ($request->header('accept') === 'text/event-stream') {
            $connection = $request->connection;
//            var_dump($connection);
            $connection->send(new Response(200, [
                'Content-Type' => 'text/event-stream'
            ], "\r\n"));

            //定时向客户推送数据
            $timerId = Timer::add(1, function () use ($connection, &$timerId) {
                // 连接关闭的时候要将定时器删除,避免定时器不断累积导致内存泄漏
                if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
                    Timer::del($timer_id);
                    return;
                }
                // 发送message事件,事件携带的数据为hello,消息id可以不传
                $connection->send(new ServerSentEvents(['event' => 'message', 'data' => 'hello', 'id' => 1]));
            });
            return;
        }
    }
}

为此你搜索到了哪些方案及不适用的原因

https://www.workerman.net/q/10107 按这里的意思?是不能在控制器里面实现吗

224 1 2
1个回答

walkor 打赏

参考下面代码

<?php
namespace app\controller;

use support\Request;
use support\Response;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\ServerSentEvents;
use Workerman\Timer;

class StreamController
{
    public function index(Request $request): Response
    {
        $connection = $request->connection;
        $id = Timer::add(1, function () use ($connection, &$id) {
            // 连接关闭时,清除定时器
            if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
                Timer::del($id);
            }
            $connection->send(new ServerSentEvents(['data' => 'hello']));
        });
        return response('', 200, [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'Connection' => 'keep-alive',
        ]);
    }

}

js

var source = new EventSource('http://127.0.0.1:8787/stream');
source.addEventListener('message', function (event) {
  var data = event.data;
  console.log(data); // 输出 hello
}, false)
  • 暂无评论
×
🔝