ImapClient.php 2.3 KB
<?php


class ImapClient {

    /**
     * 资源
     * @var resource|false
     */
    private $socket;

    protected bool $debug = false;

    protected string $host;


    /**
     * 是否是非阻塞模式
     * @var bool
     */
    public $isBlocking = false;

    public function __construct(string $host){
        $this->host = $host;
        $this->socket = false;
    }


    /**
     * 打开链接
     * @param string $out_ip 这个是出口ip
     * @param int $timeout // 连接超时时间
     * @return bool|string
     * @author:dc
     * @time 2025/3/31 9:27
     */
    public function open(string $out_ip, int $timeout=3){
        $content = stream_context_create([
            'ssl' => [
                'verify_peer' => false, // 有的证书和域名不匹配,这里关闭认证
                'verify_peer_name' => false,// 有的证书和域名不匹配,这里关闭认证
            ],
            'socket' => [
                'bindto' => $out_ip.":0" // 绑定到指定的本地 IP 地址
            ]
        ]);

        $flags = STREAM_CLIENT_CONNECT;

        $this->socket = stream_socket_client(
            $this->host,
            $errno,
            $error,
            $timeout,
            $flags,
            $content
        );


        if($error){
            return $error;
        }

        if (!$this->socket) {
            return $this->host." connection fail.";
        }

        // 设置为非阻塞模式
        $this->isBlocking = stream_set_blocking($this->socket, false);

        return true;
    }



    protected $isRead = true;

    /**
     * 写
     * @param string $cmd
     * @return false|int
     * @author:dc
     * @time 2024/9/13 15:47
     */
    public function write(string $cmd){
        error_clear_last();
        $num = @fwrite($this->socket, $cmd);
        if(!$num){
            $last = error_get_last();
            if($last){
                return $last['message']??'';
            }
        }
        return $num;
    }

    /**
     * 读
     * @return false|string
     * @author:dc
     * @time 2024/9/13 15:49
     */
    public function readLine(){

        return @fgets($this->socket,2048);

    }

    public function __destruct()
    {
        if($this->socket) @fclose($this->socket);
        unset($this->socket);
        // TODO: Implement __destruct() method.
    }

}