<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/19 8:28
 * @Description：
 *
 */

namespace Application\Command\Swoole\Client;

use Application\Service\BaseService;
use Interop\Container\ContainerInterface;

class SwLogClient extends BaseService
{
    protected $swClient;
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
        $this->swClient = new \Swoole\Client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        self::connect();
    }

    /**
     * @files.saveConflictResolution: overwriteFileOnDisk
     * @Description: 连接swoole服务器
     * @Author: llbjj
     * @Date: 2022-07-04 20:23:15
     * @return {*}
     */
    private function connect() {
        $svConfigData = [
            'ip' => '127.0.0.1',
            'port' => 9509,
            'timeout' => -1
        ];
        $isConnect = $this->swClient->connect($svConfigData['ip'], $svConfigData['port'], $svConfigData['timeout']);
        if(!$isConnect) {
            throw new \Exception("connect failed. Error: {".$this->swClient->errCode."}\n");
        }
    }

    /**
     * @files.saveConflictResolution: overwriteFileOnDisk
     * @Description: 关闭swoole客户端
     * @Author: llbjj
     * @Date: 2022-07-04 20:25:50
     * @return {*}
     */    
    private function close() {
        $this->swClient->close();
    }
    /**
     * Notes: 投递日志异步任务
     * User: llbjj
     * DateTime: 2022/5/19 8:54
     *
     */
    public function send($data){
        if(is_array($data)) $data = json_encode($data);
        $data .= '|PHENOL|';
        $this->swClient->send($data);
        self::close();
    }
}