Skip to content

Commit

Permalink
Create sync client at uri setting, and connect it only once.
Browse files Browse the repository at this point in the history
Fixed async client close warning.
  • Loading branch information
andot committed Jun 16, 2015
1 parent 2c24d82 commit 2511e52
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/Hprose/Swoole/Socket/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class Client extends \Hprose\Client {
);
public $setting = array();
private $conn_stats = array();
private $sync_client;
private $type = SWOOLE_TCP;
private $host = "";
private $port = 0;
Expand Down Expand Up @@ -94,6 +95,7 @@ private function initUrl($url) {
default:
throw new \Exception("Only support tcp, tcp4, tcp6 or unix scheme");
}
$this->sync_client = new \swoole_client($this->type | SWOOLE_KEEP);
}
else {
throw new \Exception("Can't parse this url: " . $url);
Expand All @@ -112,17 +114,19 @@ public function set($setting) {
$this->setting = array_replace($this->setting, $setting);
}
protected function sendAndReceive($request) {
$client = new \swoole_client($this->type | SWOOLE_KEEP);
$setting = array_replace($this->setting, self::$default_setting);
if (!isset($setting['package_max_length'])) {
$setting['package_max_length'] = $this->return_bytes(ini_get('memory_limit'));
}
if ($setting['package_max_length'] < 0) {
$setting['package_max_length'] = 0x7fffffff;
}
$client->set($setting);
if (!$client->connect($this->host, $this->port, $this->timeout / 1000)) {
throw new \Exception("connect failed");
$client = $this->sync_client;
if ($client->sock == 0 || !$client->isConnected()) {
$setting = array_replace($this->setting, self::$default_setting);
if (!isset($setting['package_max_length'])) {
$setting['package_max_length'] = $this->return_bytes(ini_get('memory_limit'));
}
if ($setting['package_max_length'] < 0) {
$setting['package_max_length'] = 0x7fffffff;
}
$client->set($setting);
if (!$client->connect($this->host, $this->port, $this->timeout / 1000)) {
throw new \Exception("connect failed");
}
}
if ($this->send($client, $request)) {
$response = $this->recv($client);
Expand Down Expand Up @@ -159,12 +163,12 @@ protected function asyncSendAndReceive($request, $use) {
});
$client->on("receive", function($cli, $data) use ($self, $use) {
swoole_timer_clear($cli->timer);
$cli->close();
try {
$self->sendAndReceiveCallback(substr($data, 4), null, $use);
}
catch(\Exception $e) {
}
swoole_timer_after(0, function () use ($cli) { $cli->close(); });
});
$client->on("close", function($cli) {});
$client->connect($this->host, $this->port);
Expand Down

0 comments on commit 2511e52

Please sign in to comment.