Files
kiri-rpc/TraitTransporter.php
T

79 lines
1.4 KiB
PHP
Raw Normal View History

2021-10-28 18:24:46 +08:00
<?php
namespace Kiri\Rpc;
use Exception;
use Kiri\Context;
use Swoole\Client;
use Swoole\Coroutine;
trait TraitTransporter
{
protected array $config;
2021-11-29 15:18:09 +08:00
protected array $clients = [];
2021-10-28 18:24:46 +08:00
/**
* @param $config
* @return $this
*/
public function withConfig($config): static
{
$this->config = $config;
return $this;
}
/**
* @param Client|Coroutine\Client $client
* @param $content
2021-10-28 18:31:25 +08:00
* @param bool $isClose
2021-10-28 18:24:46 +08:00
* @return mixed
*/
2021-10-28 18:31:25 +08:00
private function request(Client|Coroutine\Client $client, $content, bool $isClose): mixed
2021-10-28 18:24:46 +08:00
{
$client->send($content);
$read = $client->recv();
2021-10-28 18:31:25 +08:00
if ($isClose) {
$client->close();
}
2021-10-28 18:24:46 +08:00
return $read;
}
/**
* @return Client|Coroutine\Client
* @throws Exception
*/
private function newClient(): Coroutine\Client|Client
{
2021-11-29 15:18:09 +08:00
$alias = $this->alias($this->config);
$client = $this->clients[$alias] ?? null;
if (is_null($client)) {
$client = Context::inCoroutine() ? new Coroutine\Client(SWOOLE_SOCK_TCP) : new Client(SWOOLE_SOCK_TCP);
$this->clients[$alias] = $client;
2021-10-28 18:24:46 +08:00
}
2021-12-02 16:13:57 +08:00
[$host, $port] = [$this->config['Address'], $this->config['Port']];
2021-11-29 15:18:09 +08:00
if (!$client->isConnected() && !$client->connect($host, $port, 60)) {
2021-10-28 18:24:46 +08:00
throw new Exception('connect fail.');
}
return $client;
}
/**
2021-11-29 15:18:09 +08:00
* @param array $config
* @return string
2021-10-28 18:24:46 +08:00
*/
2021-11-29 15:18:09 +08:00
private function alias(array $config): string
2021-10-28 18:24:46 +08:00
{
2021-12-02 16:13:57 +08:00
return $config['Address'] . '::' . $config['Port'];
2021-10-28 18:24:46 +08:00
}
}