wujunxiong 4725452b86 初始版本提交 2 лет назад
..
src 4725452b86 初始版本提交 2 лет назад
LICENSE 4725452b86 初始版本提交 2 лет назад
README.md 4725452b86 初始版本提交 2 лет назад
composer.json 4725452b86 初始版本提交 2 лет назад

README.md

socket


use EasySwoole\Socket\AbstractInterface\Controller;
use EasySwoole\Socket\AbstractInterface\ParserInterface;
use EasySwoole\Socket\Bean\Response;
use EasySwoole\Socket\Bean\Caller;

class C extends Controller{

    private $hit = 0;
    protected $hitTime = 0;

    function __construct()
    {
        var_dump('controller create  '.spl_object_hash($this));
        parent::__construct();
    }

    protected function onRequest(?string $actionName): bool
    {

        $this->hit++;
        $this->hitTime = time();
        return true;
    }

    function test()
    {
        var_dump($this->hit,$this->hitTime);
//        co::sleep(10);
        $this->response()->setMessage('time:'.time());
    }

    protected function gc()
    {
        parent::gc(); // TODO: Change the autogenerated stub
        var_dump('controller has ben gc');
    }
}

class Parser implements ParserInterface{

    public function decode($raw, $client): ?Caller
    {
        // TODO: Implement decode() method.
        $ret =  new Caller();
        $ret->setControllerClass(C::class);
        $ret->setAction('test');
        return $ret;
    }

    /*
     * 如果这里返回null,则不给客户端任何数据
     */
    public function encode(Response $response, $client): ?string
    {
        // TODO: Implement encode() method.
        return $response->__toString();
    }

}

$server = new \Swoole\Server("127.0.0.1", 9501);
$server->set([
    'worker_num'=>1
]);

$conf = new \EasySwoole\Socket\Config();
$conf->setType($conf::TCP);
$conf->setParser(new Parser());
$conf->setMaxPoolNum(2);
$conf->setOnExceptionHandler(function (\swoole_server $server,\Throwable $throwable,string $raw,$client,Response $response){
    $response->setStatus('error');
    $response->setStatus($response::STATUS_RESPONSE_AND_CLOSE);
});

$dispatch = new \EasySwoole\Socket\Dispatcher($conf);
$server->on('receive', function ($server, $fd, $reactor_id, $data)use($dispatch) {
    $dispatch->dispatch($server,$data,$fd,$reactor_id);
});
$server->on('close', function ($server, $fd) {
    echo "connection close: {$fd}\n";
});
$server->start();