为了复用EventSource的长连接,我把$request->connection存放在一个自己写的类(PRefsGlobal)的成员变量下面(尝试过把这个静态类文件放在support目录下面并配置自动加载,或者把这个文件直接放到model下),并且在与其他进程通信的时候从里面拿出来推送信息给用户。
public function load(Request $request)
{
$dirname = $request->get('dirname');
if (!empty($dirname) && file_exists($dirname)) {
$task_connection = new AsyncTcpConnection('text://0.0.0.0:8888');
$task_connection->send(loadmsg($dirname));
$task_connection->onMessage = function (AsyncTcpConnection $task_connection, $task_result) {
PRefsGlobal::get("loadsse")->send(ssemessage($task_result));
if ($task_result == "Loading finished.") {
$task_connection->close();
PRefsGlobal::get("loadsse")->close();
}
};
$task_connection->connect();
return ok("success");
}
return error(404, "Wrong dirname!");
}
public function loadsse(Request $request)
{
return $this->establishsse($request, "loadsse");
}
private function establishsse(Request &$request, $name)
{
$connection = $request->connection;
if ($request->header('accept') === 'text/event-stream') {
// 首先发送一个 Content-Type: text/event-stream 头的响应
$connection->send(new Response(200, ['Content-Type' => 'text/event-stream', 'Access-Control-Allow-Origin' => '*']));
PRefsGlobal::set($name, $connection);
return new ServerSentEvents(['event' => 'message', 'data' => 'hello', 'id' => 1]);
}
return ok("ok");
}
prefsglobal类的代码
期待由eventsource返回的处理进程的结果
实际结果
访问/api/loadsse接口
"workerman/webman-framework": "^1.4.3"
1、进程间是隔离的,A进程PRefsGlobal存储了connection,在B进程是取不到的
2、
PRefsGlobal::set('loadsse ', $connection);
时打印下日志,PRefsGlobal::get("loadsse")->send(ssemessage($task_result));
前也打印下日志,看下有没有执行得到PRefsGlobal::set
,并且顺序是正确的