<?php

require_once "Auth.php";
require_once "SmtpClient.php";


class ProxyService
{

    /**
     * 连接数
     * @var SmtpClient[]
     */
    private $clients = [];


    protected function push($msg){

        if(substr($msg,-2)!=="\r\n"){
            $msg .= "\r\n";
        }
        // echo 'out '.$msg;
        return $msg;
    }

    /**
     * @author:dc
     * @time 2025/3/29 14:34
     */
    public function run()
    {
        //创建Server对象,监听 127.0.0.1:9501 端口。
        $server = new Swoole\Server(
            '0.0.0.0', 9527,
            SWOOLE_BASE,
            SWOOLE_SOCK_TCP//|SWOOLE_SSL
        );
        $server->set([
            'dispatch_mode'  =>  2 // 固定模式
        ]);
        //监听连接进入事件。
        $server->on('Connect', function ($server, $fd) {

            $server->send($fd, $this->push("220 proxy client ok\r\n"));
        });

        //监听数据接收事件。
        $server->on('Receive', function (Swoole\Server $server, $fd, $reactor_id, $data) {
            // echo "in ".rand(10,99)." > ".$data;
//            $ridfid = $reactor_id.'_'.$fd;
            if(empty($this->clients[$fd])){
                $this->clients[$fd] = new SmtpClient();
            }

            $client = $this->clients[$fd];
            // 加锁
            $client->lock();
            // 处理数据
            $result = $client->exec($data);
            // 解锁
            $client->unlock();
            // 返回结果
            $server->send($fd, $this->push($result[1]));
            // 是否关闭连接
            if($result[0]===false){
                // 关闭并释放资源
                $client->close();
                $this->clients[$fd] = null;
                unset($this->clients[$fd]);

                $server->close($fd,true);
            }
        });

        //监听连接关闭事件。
        $server->on('Close', function ($server, $fd) {
            echo '连接关闭了 => '.$fd."\n";
            $this->clients[$fd] = null;
            unset($this->clients[$fd]);
        });

        //启动服务器
        $server->start();
    }

}


(new ProxyService())->run();