You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.7 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. <?PHP
  2. namespace blobt\airpc;
  3. use Swoole;
  4. use blobt\airpc\Pack;
  5. /**
  6. * 基于swoole的轻量及 RPC
  7. * 服务器
  8. *
  9. */
  10. class RpcServer extends BaseService {
  11. /**
  12. * @var string rpc项目入口文件
  13. */
  14. public $entryPoint = false;
  15. /**
  16. * 初始化
  17. */
  18. public function init() {
  19. if (empty($this->entryPoint)) {
  20. die("Please set the entry point." . PHP_EOL);
  21. }
  22. $this->setProtocol(Pack::$packageLengthType, Pack::$packageMaxLength, Pack::$packageLengthOffset, Pack::$packageBodyOffset);
  23. }
  24. /**
  25. * 发送数据
  26. * @param integral $fd 链接文件描述付
  27. * @param string $data
  28. * @return boolean
  29. */
  30. public function send(int $fd, string $data) {
  31. $pack = new Pack($data);
  32. $this->server->send($fd, (string) $pack);
  33. }
  34. /**
  35. *
  36. * @param Swoole\Server $server
  37. * @param int $fd
  38. * @param int $reactorId
  39. * @param string $pack
  40. */
  41. public function onReceive(Swoole\Server $server, int $fd, int $reactorId, string $pack) {
  42. $pack = new Pack($pack);
  43. $data = $pack->data;
  44. $this->handle($fd, $data);
  45. }
  46. /**
  47. * 请求处理函数
  48. * @param int $fd
  49. * @param string $pack
  50. */
  51. public function handle(int $fd, string $data) {
  52. $_SERVER['data'] = $data;
  53. try {
  54. $ret = include $this->entryPoint;
  55. $this->send($fd, $ret);
  56. } catch (\Error $e) {
  57. //TODO 记录日志
  58. print_r($e);
  59. $this->send($fd, "YeeError");
  60. } catch (\Exception $e) {
  61. //TODO 记录日志
  62. print_r($e);
  63. $this->send($fd, "YeeException");
  64. }
  65. }
  66. }