SwooleClient.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/5/4
  6. * Time: 上午11:22
  7. */
  8. namespace anlity\swooleAsyncTimer\src;
  9. class SwooleClient
  10. {
  11. public $option = [
  12. 'host' => '',
  13. 'port' => '',
  14. 'timeout' => 30,
  15. 'data' => '',
  16. ];
  17. private $_client;
  18. private $_errors = [];
  19. public function __construct()
  20. {
  21. }
  22. public function setOption($attr, $value){
  23. $this->option[$attr] = $value;
  24. }
  25. /**
  26. * 发送请求
  27. * @return bool|string
  28. * @throws \Exception
  29. */
  30. public function post(){
  31. $this->_client = new SWebSocket($this->option['host'], $this->option['port']);
  32. if (!$this->_client->connect($this->option['timeout'])) {
  33. $this->addError('connect', "服务器连接失败. Error: {$this->_client->errCode}");
  34. return false;
  35. }
  36. $this->_client->send($this->option['data']);
  37. $result = $this->_client->recv();
  38. $this->_client->disconnect();
  39. if($result === false){
  40. $this->addError('send', "参数发送失败,Error:{$this->_client->errCode}");
  41. }
  42. return $result;
  43. }
  44. /**
  45. * @param $attr
  46. * @param $message
  47. */
  48. public function addError($attr, $message){
  49. $this->_errors[$attr][] = $message;
  50. }
  51. /**
  52. * @return array
  53. */
  54. public function getError(){
  55. return $this->_errors;
  56. }
  57. }