PHPackages                             webnarmin/amphp-websocket-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. webnarmin/amphp-websocket-server

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

webnarmin/amphp-websocket-server
================================

A WebSocket server with HTTP control and authentication

v1.0.0(2y ago)110MITPHPPHP &gt;=8.1CI passing

Since Jun 29Pushed 1w agoCompare

[ Source](https://github.com/webnarmin/amphp-websocket-server)[ Packagist](https://packagist.org/packages/webnarmin/amphp-websocket-server)[ RSS](/packages/webnarmin-amphp-websocket-server/feed)WikiDiscussions main Synced 1mo ago

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

AmPHP WebSocket Server
======================

[](#amphp-websocket-server)

Authenticated WebSocket transport runtime on top of Amp.

This package provides:

- WebSocket server bootstrap using `amphp/websocket-server`.
- Authentication for WebSocket clients and HTTP control requests.
- Strict JSON message envelopes.
- Explicit action routing.
- User-aware gateway for direct, multicast and broadcast delivery.
- HTTP control endpoints for pushing messages from another process.

It does not provide application-level chat flows, UI rendering, persistence, rooms, bot logic or framework-specific abstractions. Libraries such as ChatFlow can use this package as a transport layer.

Installation
------------

[](#installation)

```
composer require webnarmin/amphp-websocket-server
```

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

[](#quick-start)

```
use webnarmin\AmphpWS\ActionRouter;
use webnarmin\AmphpWS\Configurator;
use webnarmin\AmphpWS\Protocol\ResponseEnvelope;
use webnarmin\AmphpWS\Simple\SimpleAuthenticator;
use webnarmin\AmphpWS\WebSocketServer;

$router = new ActionRouter();

$router->on('echo', static function ($user, $message): ResponseEnvelope {
    return ResponseEnvelope::success([
        'message' => 'Echo: ' . ($message->getPayload()['message'] ?? ''),
    ]);
});

$server = new WebSocketServer(
    new Configurator([
        'websocket' => ['host' => '127.0.0.1', 'port' => 1337],
        'allow_origins' => ['http://127.0.0.1:8000'],
    ]),
    new SimpleAuthenticator('control-http-auth-token', 'websocket-signing-secret'),
    $router,
);

$server->run();
```

Message Protocol
----------------

[](#message-protocol)

Clients send JSON objects:

```
{
  "action": "echo",
  "payload": {"message": "Hello"},
  "requestId": "req-1",
  "metadata": {"source": "browser"}
}
```

Rules:

- `action` is required and must be a non-empty string.
- `payload` is optional and must be a JSON object when present.
- `requestId` is optional and must be a non-empty string when present.
- `metadata` is optional and must be a JSON object when present.

Server responses use:

```
{
  "status": "success",
  "payload": {"message": "Echo: Hello"},
  "requestId": "req-1"
}
```

Errors use:

```
{
  "status": "error",
  "payload": {},
  "requestId": "req-1",
  "error": {"code": "unsupported_action", "message": "Action 'x' is not supported."}
}
```

Standard error codes:

- `invalid_json`
- `invalid_message`
- `unsupported_action`
- `handler_failed`
- `authentication_failed`
- `invalid_control_request`

Action Handlers
---------------

[](#action-handlers)

Handlers may be callables or implement `MessageHandlerInterface`.

```
$router->on('sum', static function ($user, $message): ResponseEnvelope {
    $numbers = $message->getPayload()['numbers'] ?? [];

    return ResponseEnvelope::success([
        'result' => is_array($numbers) ? array_sum($numbers) : 0,
    ]);
});
```

Return `null` when no response should be sent. Return `ResponseEnvelope::success([])` when an explicit empty success response should be sent.

Authentication
--------------

[](#authentication)

Implement `Authenticator`:

```
interface Authenticator
{
    public function authenticateControlHttp(Request $request): bool;
    public function authenticateWebSocket(Request $request): ?WebsocketUser;
}
```

`WebsocketUser::getId()` returns a non-null positive integer. If WebSocket authentication fails, the client is closed with policy violation code `1008`.

`SimpleAuthenticator` is a minimal HMAC-signed token example. For production systems, implement `Authenticator` against your own session, API token or identity provider.

Gateway
-------

[](#gateway)

Use `getGateway()` to send messages to authenticated users:

```
$server->getGateway()->sendText(123, 'Hello user');
$server->getGateway()->multicastText('Hello team', [123, 456]);
$server->getGateway()->broadcastText('Hello everyone', excludedUserIds: [123]);
```

If a user has no active client, sending is a no-op handled by Amp's gateway. Invalid user ids are rejected with `GatewayException`.

HTTP Control
------------

[](#http-control)

Authenticated POST endpoints:

- `/send-text`
- `/broadcast-text`
- `/broadcast-binary`
- `/multicast-text`
- `/multicast-binary`

Successful response:

```
{"status":"success"}
```

Error response:

```
{"status":"error","error":{"code":"invalid_control_request","message":"payload must be a string."}}
```

Use `WebsocketControlHttpClient` from CLI or workers:

```
$result = $client->sendText(123, 'Hello');

if (!$result->isSuccess()) {
    echo $result->getMessage();
}
```

Lifecycle Hooks
---------------

[](#lifecycle-hooks)

`ServerHooks` supports optional callbacks:

- authenticated: called after a client is authenticated and registered.
- disconnected: called when a registered client disconnects.
- invalidMessage: called when inbound JSON/protocol validation fails.
- unhandledException: called for authentication and handler/runtime failures.

Examples
--------

[](#examples)

- `example/server.php` starts a router-based server.
- `example/public/index.php` is a browser test client.
- `example/broadcast_from_cli.php` sends a control HTTP broadcast.

Quality
-------

[](#quality)

```
composer check
composer cs-check
```

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance64

Regular maintenance activity

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

734d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4216840?v=4)[webnarmin](/maintainers/webnarmin)[@webnarmin](https://github.com/webnarmin)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/webnarmin-amphp-websocket-server/health.svg)

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

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.3k543.5M2.6k](/packages/aws-aws-sdk-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k656.1k38](/packages/neuron-core-neuron-ai)[illuminate/http

The Illuminate Http package.

11937.9M6.9k](/packages/illuminate-http)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3741.3M47](/packages/tencentcloud-tencentcloud-sdk-php)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)[guzzlehttp/test-server

Node.js server and PHP controller

14284.0k22](/packages/guzzlehttp-test-server)

PHPackages © 2026

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