PHP code example of easyswoole / socket

1. Go to this page and download the library: Download easyswoole/socket library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

easyswoole / socket example snippets



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->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();