TCP Server

框架提供原始的 TCPServer, 由 \FastD\Servitization\Server\TCPServer 提供。实现代码如下:

  1. <?php
  2. namespace FastD\Servitization\Server;
  3. use FastD\Http\ServerRequest;
  4. use FastD\Packet\Json;
  5. use FastD\Servitization\OnWorkerStart;
  6. use FastD\Swoole\Server\TCP;
  7. use swoole_server;
  8. class TCPServer extends TCP
  9. {
  10. use OnWorkerStart;
  11. public function doWork(swoole_server $server, $fd, $data, $from_id)
  12. {
  13. if ('quit' === $data) {
  14. $server->close($fd);
  15. return 0;
  16. }
  17. $data = Json::decode($data);
  18. $request = new ServerRequest($data['method'], $data['path']);
  19. if (isset($data['args'])) {
  20. if ('GET' === $request->getMethod()) {
  21. $request->withQueryParams($data['args']);
  22. } else {
  23. $request->withParsedBody($data['args']);
  24. }
  25. }
  26. $response = app()->handleRequest($request);
  27. $server->send($fd, (string) $response->getBody());
  28. app()->shutdown($request, $response);
  29. return 0;
  30. }
  31. }

主要核心接受 json 格式数据,由 FastD\Packet\Json 对象进行处理。因此 TCPServer 接受需要接受 json 格式的数据,例如:

  1. {
  2. "path": "/",
  3. "args": []
  4. }