HttpServer.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. use Workerman\Connection\TcpConnection;
  4. use Workerman\Protocols\Http\Request;
  5. use Workerman\Protocols\Http\Response;
  6. use Workerman\Protocols\Http\ServerSentEvents;
  7. use Workerman\Timer;
  8. use Workerman\Worker;
  9. require_once __DIR__ . '/vendor/autoload.php';
  10. if (!defined('STDIN')) define('STDIN', fopen('php://stdin', 'r'));
  11. if (!defined('STDOUT')) define('STDOUT', fopen('php://stdout', 'w'));
  12. if (!defined('STDERR')) define('STDERR', fopen('php://stderr', 'w'));
  13. $worker = new Worker('http://127.0.0.1:8080');
  14. $worker->onMessage = function (TcpConnection $connection, Request $request) {
  15. match ($request->path()) {
  16. '/' => $connection->send('Hello Chance'),
  17. '/get' => $connection->send(json_encode($request->get())),
  18. '/post' => $connection->send(json_encode($request->post())),
  19. '/header' => $connection->send($request->header('foo')),
  20. '/setSession' => (function () use ($connection, $request) {
  21. $request->session()->set('foo', 'bar');
  22. $connection->send('');
  23. })(),
  24. '/session' => $connection->send($request->session()->pull('foo')),
  25. '/sse' => (function () use ($connection) {
  26. $connection->send(new Response(200, ['Content-Type' => 'text/event-stream'], "\r\n"));
  27. $i = 0;
  28. $timer_id = Timer::add(0.001, function () use ($connection, &$timer_id, &$i) {
  29. if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
  30. Timer::del($timer_id);
  31. return;
  32. }
  33. if ($i >= 5) {
  34. Timer::del($timer_id);
  35. $connection->close();
  36. return;
  37. }
  38. $i++;
  39. $connection->send(new ServerSentEvents(['data' => "hello$i"]));
  40. });
  41. })(),
  42. '/file' => $connection->send(json_encode($request->file('file'))),
  43. default => $connection->send(new Response(404, [], '404 not found'))
  44. };
  45. };
  46. Worker::$command = 'start';
  47. Worker::runAll();