Hyperf-Socket.io實現私聊

php迷途小書童發表於2021-04-06

gitee地址

:point_down:部分程式碼

鑑權

class WebSocketAuthMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 虛擬碼,透過 isAuth 方法攔截握手請求並實現許可權檢查
        if (! $this->isAuth($request)) {
            throw new WebsocketException(401, 'auth faild');
        }
        return $handler->handle($request);
    }

    public function isAuth($request)
    {
        $params = $request->getQueryParams();

        $user = User::query()
            ->where('token', $params['token'])
            ->first();
        if (!$user)
            return false;
        $request = Context::get(ServerRequestInterface::class);
        $request = $request->withAttribute('user', $user);
        Context::set(ServerRequestInterface::class, $request);
        return true;
    }
}

控制器

/**
 * @SocketIONamespace("/")
 */
class WebSocketController extends BaseNamespace
{
    /**
     * @Inject 
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @Event("connect")
     */
    public function connect(Socket $socket)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 這裡 dispatch(object $event) 會逐個執行監聽該事件的監聽器
        $this->eventDispatcher->dispatch(new SocketIoConnect($user, $socket->getSid()));
    }

    /**
     * @Event("disconnect")
     */
    public function disconnect(Socket $socket)
    {
        $user = $socket->getRequest()->getAttribute('user');
        // 這裡 dispatch(object $event) 會逐個執行監聽該事件的監聽器
        $this->eventDispatcher->dispatch(new SocketIoDisConnect($user));
    }

    /**
     * @Event("say")
     * @param string $data
     */
    public function onSay(Socket $socket, $data)
    {
        // 這裡 dispatch(object $event) 會逐個執行監聽該事件的監聽器
        $this->eventDispatcher->dispatch(new UserChat($data));
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章