true, // 开启协议解析 'package_length_type' => 'N', // 长度字段的类型 'package_length_offset' => 0, //第几个字节是包长度的值 'package_body_offset' => PACKAGE_BODY_OFFSET, //第几个字节开始计算包内容 'package_max_length' => PACKAGE_MAXLENG, //协议最大长度 ]; $type = SWOOLE_SOCK_TCP; if($options['ssl'] == true){ $type |= SWOOLE_SSL; $sslConfig = [ 'ssl_cert_file' => $options['ssl_cert_file'], 'ssl_key_file' => $options['ssl_key_file'], ]; $buildSwooleConfig = array_merge($buildSwooleConfig, $sslConfig); } $this->client = new \Swoole_Client($type); $this->client->set($buildSwooleConfig); if(!$this->client->connect($options['host'], $options['port'], isset($options['time_out'])?$options['time_out']:5)){ throw new \Exception("connect failed. Error:".$this->client->errCode.PHP_EOL); } } /** * 发送Swoole 数据 */ public function sendMsg($msg) { //发送给消息到服务端 //$this->client->send( $this->formatMsg($msg) ); $this->client->send( "hello world\n" ); //接受服务端发来的信息 $message = $this->client->recv(); $message = json_decode(substr($message, 12),true); //关闭客户端 $this->client->close(); return $message; } public function formatMsg($msg) { return json_encode($msg, JSON_UNESCAPED_UNICODE).PACKAGE_EOF; } }