Skip to content

Commit c978852

Browse files
committed
optimize client
1 parent 8e050ce commit c978852

File tree

1 file changed

+44
-9
lines changed

1 file changed

+44
-9
lines changed

src/Client.php

Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -307,22 +307,50 @@ public function onError(swoole_client $client) {}
307307
*/
308308
public function onClose(swoole_client $client) {}
309309

310+
/**
311+
* @return bool
312+
*/
313+
public function isConnected()
314+
{
315+
return $this->client->isConnected();
316+
}
317+
318+
/**
319+
* @return mixed
320+
*/
321+
public function receive()
322+
{
323+
return $this->client->recv();
324+
}
325+
326+
/**
327+
* @return mixed
328+
*/
329+
public function close()
330+
{
331+
return $this->client->close();
332+
}
333+
310334
/**
311335
* @param string|array $data
312336
* @return mixed
313337
*/
314338
public function send($data = '')
315339
{
316-
if (null === $this->client) {
317-
throw new LogicException('Please call the createRequest method first');
318-
}
319-
if ( ! $this->client->connect($this->host, $this->port, $this->timeout)) {
320-
throw new RuntimeException(socket_strerror($this->client->errCode));
321-
}
340+
if (!$this->isConnected()) {
341+
if (null === $this->client) {
342+
throw new LogicException('Please call the createRequest method first');
343+
}
344+
if ( ! $this->client->connect($this->host, $this->port, $this->timeout)) {
345+
throw new RuntimeException(socket_strerror($this->client->errCode));
346+
}
322347

323-
$this->client->send($this->wrapBody($data));
324-
$receive = $this->client->recv();
325-
$this->client->close();
348+
$this->client->send($this->wrapBody($data));
349+
$receive = $this->receive();
350+
} else {
351+
$this->client->send($this->wrapBody($data));
352+
$receive = $this->receive();
353+
}
326354

327355
return $receive;
328356
}
@@ -337,4 +365,11 @@ public function start()
337365
}
338366
$this->client->connect($this->host, $this->port, $this->timeout);
339367
}
368+
369+
public function __destruct()
370+
{
371+
if ($this->isConnected()) {
372+
$this->close();
373+
}
374+
}
340375
}

0 commit comments

Comments
 (0)