前端使用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 按这里的意思?是不能在控制器里面实现吗
参考下面代码
js