IndexController.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace plugin\saipackage\app\controller;
  3. use plugin\saiadmin\basic\OpenController;
  4. use Saithink\Saipackage\service\Terminal;
  5. use support\Request;
  6. use support\Response;
  7. use Throwable;
  8. use Workerman\Protocols\Http\ServerSentEvents;
  9. class IndexController extends OpenController
  10. {
  11. /**
  12. * 执行终端
  13. * @param Request $request
  14. * @return void
  15. * @throws Throwable
  16. */
  17. public function terminal(Request $request): void
  18. {
  19. // SSE 消息
  20. $connection = $request->connection;
  21. $connection->send(new Response(200, [
  22. 'Content-Type' => 'text/event-stream',
  23. 'Cache-Control' => 'no-cache',
  24. 'Connection' => 'keep-alive',
  25. 'X-Accel-Buffering' => 'no',
  26. 'Access-Control-Allow-Origin' => '*',
  27. 'Access-Control-Allow-Credentials' => 'true',
  28. 'Access-Control-Expose-Headers' => 'Content-Type',
  29. ], "\r\n"));
  30. // 消息开始
  31. $connection->send(new ServerSentEvents([
  32. 'event' => 'message', 'data' => 'start'
  33. ]));
  34. // 生成器
  35. $generator = (new Terminal())->exec();
  36. foreach ($generator as $chunk) {
  37. $connection->send(new ServerSentEvents([
  38. 'event' => 'message', 'data' => $chunk
  39. ]));
  40. }
  41. // 关闭链接
  42. $connection->close();
  43. }
  44. }