Client.Class.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Mall\Framework\Swoole;
  3. class Client{
  4. private $client;
  5. private $clients = [];
  6. private $waitList = [];
  7. public function __construct($options){
  8. class_exists('Swoole_Client') or die("Swoole_Client: check swoole extension");
  9. $buildSwooleConfig = [
  10. 'open_length_check' => true, // 开启协议解析
  11. 'package_length_type' => 'N', // 长度字段的类型
  12. 'package_length_offset' => 0, //第几个字节是包长度的值
  13. 'package_body_offset' => PACKAGE_BODY_OFFSET, //第几个字节开始计算包内容
  14. 'package_max_length' => PACKAGE_MAXLENG, //协议最大长度
  15. ];
  16. $type = SWOOLE_SOCK_TCP;
  17. if($options['ssl'] == true){
  18. $type |= SWOOLE_SSL;
  19. $sslConfig = [
  20. 'ssl_cert_file' => $options['ssl_cert_file'],
  21. 'ssl_key_file' => $options['ssl_key_file'],
  22. ];
  23. $buildSwooleConfig = array_merge($buildSwooleConfig, $sslConfig);
  24. }
  25. $this->client = new \Swoole_Client($type);
  26. $this->client->set($buildSwooleConfig);
  27. if(!$this->client->connect($options['host'], $options['port'], isset($options['time_out'])?$options['time_out']:5)){
  28. throw new \Exception("connect failed. Error:".$this->client->errCode.PHP_EOL);
  29. }
  30. }
  31. /**
  32. * 发送Swoole 数据
  33. */
  34. public function sendMsg($msg)
  35. {
  36. //发送给消息到服务端
  37. //$this->client->send( $this->formatMsg($msg) );
  38. $this->client->send( "hello world\n" );
  39. //接受服务端发来的信息
  40. $message = $this->client->recv();
  41. $message = json_decode(substr($message, 12),true);
  42. //关闭客户端
  43. $this->client->close();
  44. return $message;
  45. }
  46. public function formatMsg($msg)
  47. {
  48. return json_encode($msg, JSON_UNESCAPED_UNICODE).PACKAGE_EOF;
  49. }
  50. }