swoole4 websocket + pdo连接池

<?php
declare(strict_types=1);
namespace app\api\controller\yy;

use app\common\controller\Api;
use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;
use think\Controller;
class Websocket{

    protected $pool = null;
    public function __construct(){

        //创建WebSocket Server对象,监听0.0.0.0:9502端口。
        $ws = new \Swoole\WebSocket\Server('0.0.0.0', 9307);

        $this->pool = new PDOPool((new PDOConfig)
            ->withHost('')
            ->withPort(3306)
            // ->withUnixSocket('/tmp/mysql.sock')
            ->withDbName('')
            ->withCharset('utf8mb4')
            ->withUsername('')
            ->withPassword('')
        );

        //监听WebSocket连接打开事件。
        $ws->on('Open', function ($ws, $request) {
            $ws->push($request->fd, "hello, welcome\n");
        });

        //监听WebSocket消息事件。
        $ws->on('Message', function ($ws, $frame) {
            echo "Message: {$frame->data}\n";
            $this->pdo();
            $ws->push($frame->fd, "server: {$frame->data}");
        });

        //监听WebSocket连接关闭事件。
        $ws->on('Close', function ($ws, $fd) {
            echo "client-{$fd} is closed\n";
        });

        $ws->start();
    }

    public function pdo()
    {
        $pdo = $this->pool->get();
        $statement = $pdo->query("SELECT * from ***")->fetch();
        var_dump($statement);
        $this->pool->put($pdo);
    }
}

new Websocket();

 

posted @ 2024-07-19 20:08  祈愿仙帝  阅读(7)  评论(0编辑  收藏  举报