PHPackages                             php-websocket-rpc/rpc-server - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. php-websocket-rpc/rpc-server

ActiveLibrary[HTTP &amp; Networking](/categories/http)

php-websocket-rpc/rpc-server
============================

Async RPC server over WebSocket using amphp and msgpack

v0.1.0(1mo ago)04MITPHPPHP &gt;=8.5

Since Jun 10Pushed 2mo agoCompare

[ Source](https://github.com/php-websocket-rpc/rpc-server)[ Packagist](https://packagist.org/packages/php-websocket-rpc/rpc-server)[ Docs](https://github.com/php-websocket-rpc/rpc-server)[ RSS](/packages/php-websocket-rpc-rpc-server/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (7)Versions (2)Used By (0)

php-websocket-rpc/rpc-server
============================

[](#php-websocket-rpcrpc-server)

Async RPC server over WebSocket using amphp and msgpack.

Install
-------

[](#install)

```
composer require php-websocket-rpc/rpc-server
```

Requires PHP 8.5+, `ext-msgpack`, and the amphp ecosystem.

Quick Start
-----------

[](#quick-start)

```
use Amp\Http\Server\DefaultErrorHandler;
use Amp\Http\Server\Router;
use Amp\Http\Server\SocketHttpServer;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use Amp\Socket\InternetAddress;
use Monolog\Logger;
use PhpWebsocketRpc\RpcServer\Adapter\AmpWebSocketServerAdapter;
use PhpWebsocketRpc\RpcServer\Server\RpcServerBuilder;

// Logger
$handler = new StreamHandler(\Amp\ByteStream\getStdout());
$handler->setFormatter(new ConsoleFormatter());
$logger = new Logger('server', [$handler]);

// HTTP server
$httpServer = SocketHttpServer::createForDirectAccess($logger);
$httpServer->expose(new InternetAddress('127.0.0.1', 9502));

$errorHandler = new DefaultErrorHandler();
$router = new Router($httpServer, $logger, $errorHandler);

// Build RPC server
$server = (new RpcServerBuilder())
    ->withLogger($logger)
    ->registerService(MathService::class, new MathServiceImpl())
    ->build();

// Mount at /rpc
AmpWebSocketServerAdapter::attach($httpServer, $router, '/rpc', $server);

// Start HTTP server
$httpServer->start($router, $errorHandler);
```

The client then uses `createProxy()`:

```
$math = $client->createProxy(MathService::class);
$result = $math->add(10, 5);    // 15
```

Features
--------

[](#features)

- **Contract services** — register interface implementations, auto-dispatched via `ContractRegistry`
- **Streaming** — methods returning `Iterator` are automatically streamed to the client
- **Subscribe/Publish** — `#[RpcSubscribe]` and `#[RpcPublish]` attributes on interface methods
- **Authentication** — `useAuthentication()` with pluggable providers, `#[NeedAuthorization]` attribute
- **Middleware** — pipeline for rate limiting, logging, auth, etc.
- **Client sessions** — track connected clients with per-session attributes

Authentication &amp; Authorization
----------------------------------

[](#authentication--authorization)

You must implement `AuthenticationProvider` to validate tokens and `AuthorizationProvider` to authorize method calls. The framework provides built-in implementations for testing. The `AuthService` is automatically registered and can be used to authenticate clients. The `ClientSessionContext` is a fiber-safe accessor for session attributes.

### Quick Setup

[](#quick-setup)

```
use PhpWebsocketRpc\Rpc\Auth\User;
use PhpWebsocketRpc\RpcServer\Auth\InMemoryUserProvider;
use PhpWebsocketRpc\RpcServer\Auth\StaticTokenAuthenticationProvider;

$server = (new RpcServerBuilder())
    ->withLogger($logger)
    ->useAuthentication(
        new StaticTokenAuthenticationProvider('tok-admin', 'bob'),
        new InMemoryUserProvider([
            'bob' => new User('bob', ['admin']),
        ]),
    )
    ->registerService(SecureDataService::class, new SecureDataServiceImpl())
    ->build();
```

### Protecting Methods

[](#protecting-methods)

Use the `#[NeedAuthorization]` attribute on your contract interface:

```
use PhpWebsocketRpc\Rpc\Contract\Attribute\NeedAuthorization;

// Protect entire interface — all methods require auth
#[NeedAuthorization]
interface AdminService
{
    public function deleteUser(string $id): void;
}

// Protect specific methods only
interface ChatService
{
    public function getPublicInfo(): string;  // open to all

    #[NeedAuthorization]
    public function getProfile(): string;     // needs auth

    #[NeedAuthorization(roles: ['admin', 'moderator'])]
    public function deleteMessage(string $id): void;  // needs specific role
}
```

### Client Flow

[](#client-flow)

```
// 1. Authenticate
$auth = $client->createProxy(AuthService::class);
$user = $auth->authenticate('tok-alice');

// 2. Access protected methods
$service = $client->createProxy(ChatService::class);
$service->getProfile();                    // ✅ works after auth
$service->deleteMessage('msg-1');          // ❌ AuthorizationException (not admin)
```

### Custom Authentication Provider

[](#custom-authentication-provider)

Implement `AuthenticationProvider` to use JWT, database, or any other logic:

```
use PhpWebsocketRpc\Rpc\Auth\Token;
use PhpWebsocketRpc\Rpc\Auth\User;
use PhpWebsocketRpc\RpcServer\Auth\AuthenticationProvider;
use PhpWebsocketRpc\RpcServer\Auth\InMemoryUserProvider;
use PhpWebsocketRpc\RpcServer\Auth\UserProvider;

class JwtProvider implements AuthenticationProvider
{
    public function __construct(private string $secret) {}

    public function validateToken(#[\SensitiveParameter] string $token): ?Token
    {
        try {
            $payload = \Firebase\JWT\JWT::decode($token, $this->secret, ['HS256']);
            $now = \time();
            return new Token(
                id: \bin2hex(\random_bytes(16)),
                issuer: 'my-app',
                subject: $payload->sub,
                audience: 'rpc',
                expiresAt: $now + 3600,
                notBefore: $now,
                issuedAt: $now,
            );
        } catch (\Throwable) {
            return null;
        }
    }

    public function refreshToken(#[\SensitiveParameter] Token $token): Token
    {
        return new Token(
            id: $token->id,
            issuer: $token->issuer,
            subject: $token->subject,
            audience: $token->audience,
            expiresAt: \time() + 3600,
            notBefore: \time(),
            issuedAt: \time(),
        );
    }
}

// Must also provide a UserProvider to resolve user details from the token subject
$server = (new RpcServerBuilder())
    ->withLogger($logger)
    ->useAuthentication(
        new JwtProvider(),
        new InMemoryUserProvider([
            'alice' => new User('alice', ['customer']),
        ]),
    )
    ->build();
```

### Custom Authorization Provider

[](#custom-authorization-provider)

For fine-grained authorization (resource ownership, IP checks, etc.):

```
use PhpWebsocketRpc\RpcServer\Auth\AuthorizationProvider;
use PhpWebsocketRpc\RpcServer\Server\ClientSession;

class OwnershipProvider implements AuthorizationProvider
{
    public function authorize(
        ClientSession $session,
        string $service,
        string $method,
        ?array $requiredRoles,
    ): void {
        if ($method === 'deleteMessage') {
            // Check resource ownership from session attribute
        }
    }
}

$server = (new RpcServerBuilder())
    ->withLogger($logger)
    ->useAuthentication(
        new JwtProvider(),
        new InMemoryUserProvider([...]),
        new OwnershipProvider(),   // third arg = optional AuthorizationProvider
    )
    ->build();
```

### Statelessness

[](#statelessness)

The `AuthenticationProvider::validateToken()` method **must be stateless** for cross-replica deployments. Use JWT (self-contained) or look up from a shared store (Redis/DB). It returns a `Token` value object (id, issuer, subject, audience, expiry) — the actual user data is resolved separately via `UserProvider::getUser()`. The framework only stores the authenticated user per-WebSocket-connection in memory, which is freed on disconnect.

Contract Services
-----------------

[](#contract-services)

Define an interface with attributes:

```
use PhpWebsocketRpc\Rpc\Contract\Attribute\RpcSubscribe;
use PhpWebsocketRpc\Rpc\Contract\Attribute\RpcStream;
use PhpWebsocketRpc\Rpc\Contract\Attribute\RpcPublish;

interface MathService
{
    public function add(int $a, int $b): int;         // call/response
    public function log(string $msg): void;            // notification

    #[RpcStream]
    public function count(int $limit): \Iterator;      // streaming

    #[RpcSubscribe('events')]
    public function onEvent(callable $cb): void;       // subscribe

    #[RpcPublish('chat')]
    public function send(string $msg): void;           // publish
}
```

Register the implementation:

```
$server = (new RpcServerBuilder())
    ->withLogger($logger)
    ->registerService(MathService::class, new MathServiceImpl())
    ->build();
```

Architecture
------------

[](#architecture)

The server uses a **builder + adapter** pattern to keep the core framework-agnostic:

- **`RpcServerBuilder`** collects all configuration (services, middleware, auth) and calls `build()` to produce a configured `RpcServer`
- **`RpcServer`** is the runtime: dispatches messages, manages sessions, and streams — it has zero amphp imports in its core
- **`AmpWebSocketServerAdapter`** bridges amphp's HTTP/WebSocket layer to `RpcServer`, creating `ClientSession` on upgrade and wrapping the amp client in `Client` (from `PhpWebsocketRpc\Rpc\Transport\Amp`)
- **Transport interfaces** (`WebSocketClientInterface`, `MessageInterface`, `TlsInfoInterface`) in `PhpWebsocketRpc\Rpc\Transport` define the boundary; amp implementations live in a sub-namespace

Key Classes
-----------

[](#key-classes)

ClassPurpose`PhpWebsocketRpc\RpcServer\Server\RpcServerBuilder`Fluent builder — configure services, middleware, auth, then `build()``PhpWebsocketRpc\RpcServer\Server\RpcServer`Runtime core — dispatches messages, manages sessions, no amphp deps`PhpWebsocketRpc\RpcServer\Adapter\AmpWebSocketServerAdapter`Bridges amphp HTTP/WebSocket to `RpcServer``PhpWebsocketRpc\RpcServer\Server\RpcDispatcher`Composes middleware pipeline with router dispatch`PhpWebsocketRpc\RpcServer\Server\ContractRegistry`Manages contract service implementations`PhpWebsocketRpc\RpcServer\Server\ClientSession`Represents a connected client`PhpWebsocketRpc\RpcServer\Stream\StreamChannel`Manages a named stream channel`PhpWebsocketRpc\RpcServer\Middleware\RateLimiterMiddleware`Rate limiting middleware`PhpWebsocketRpc\RpcServer\Auth\AuthenticationProvider`Interface for token validation (returns `Token`)`PhpWebsocketRpc\RpcServer\Auth\UserProvider`Interface for resolving user details from a token subject`PhpWebsocketRpc\RpcServer\Auth\AuthorizationProvider`Interface for fine-grained authorization`PhpWebsocketRpc\RpcServer\Auth\StaticTokenAuthenticationProvider`Simple static-token auth provider`PhpWebsocketRpc\RpcServer\Auth\InMemoryUserProvider`Simple in-memory user provider for testing`PhpWebsocketRpc\RpcServer\Auth\AuthService`Built-in auth handler (auto-registered)`PhpWebsocketRpc\RpcServer\Auth\ClientSessionContext`Fiber-safe session accessor`PhpWebsocketRpc\Rpc\Transport\Amp\Client`Wraps amphp's `WebsocketClient` for `RpcServer``PhpWebsocketRpc\Rpc\Transport\FramedConnection`Serializes/deserializes `Payload` over binary WebSocket

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance89

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

44d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/023a0bd17758df473ae6dad9f07575a8d0a8c36b06e83396b5962aecba38c722?d=identicon)[PrasWicaksono](/maintainers/PrasWicaksono)

---

Top Contributors

[![praswicaksono](https://avatars.githubusercontent.com/u/603125?v=4)](https://github.com/praswicaksono "praswicaksono (1 commits)")

---

Tags

asyncrpcserverwebsocketamphprate-limitermsgpack

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/php-websocket-rpc-rpc-server/health.svg)

```
[![Health](https://phpackages.com/badges/php-websocket-rpc-rpc-server/health.svg)](https://phpackages.com/packages/php-websocket-rpc-rpc-server)
```

###  Alternatives

[amphp/http-server

A non-blocking HTTP application server for PHP based on Amp.

1.3k6.7M115](/packages/amphp-http-server)[phrity/websocket

WebSocket client and server

2164.9M41](/packages/phrity-websocket)[amphp/websocket-client

Async WebSocket client for PHP based on Amp.

1645.1M66](/packages/amphp-websocket-client)[amphp/websocket

Shared code for websocket servers and clients.

465.2M11](/packages/amphp-websocket)[api-platform/metadata

API Resource-oriented metadata attributes and factories

295.0M223](/packages/api-platform-metadata)[amphp/websocket-server

Websocket server for Amp's HTTP server.

125282.8k34](/packages/amphp-websocket-server)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
