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

ActiveLibrary

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

A WebSocket server with HTTP control and authentication

v1.0.0(1y ago)110MITPHPPHP &gt;=8.1

Since Jun 29Pushed 1y ago1 watchersCompare

[ 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)

A flexible and efficient WebSocket server implementation using the Amp concurrency framework for PHP. This library enables developers to create real-time, interactive web applications with ease, providing features such as authentication, message handling, broadcasting, and more. It is designed to be scalable and efficient, making it ideal for high-performance applications.

Features
--------

[](#features)

- **Easy Setup**: Minimal configuration required to start.
- **Authentication**: Supports authentication for WebSocket and HTTP control requests.
- **Message Handling**: Customizable actions for client messages.
- **Broadcasting**: Send messages to multiple clients at once.
- **Secure Connections**: Optional SSL/TLS support.
- **Extensible**: Easily extend and customize.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
    - [Server-side Setup](#server-side-setup)
    - [Client-side Usage](#client-side-usage)
    - [Broadcasting from CLI](#broadcasting-from-cli)
- [Configuration](#configuration)
- [Contributing](#contributing)
- [License](#license)

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

[](#installation)

Install via Composer:

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

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

[](#quick-start)

### 1. Create a WebSocket Server Class

[](#1-create-a-websocket-server-class)

First, extend the `WebSocketServer` class and define your message handlers:

```
use webnarmin\AmphpWS\WebSocketServer;
use webnarmin\AmphpWS\Contracts\WebsocketUser;

class MyWebSocketServer extends WebSocketServer
{
    protected function handleEcho(WebsocketUser $user, array $payload): array
    {
        return ['message' => 'Echo: ' . $payload['message']];
    }

    protected function handleSum(WebsocketUser $user, array $payload): array
    {
        $numbers = $payload['numbers'] ?? [];
        $sum = array_sum($numbers);
        return ['result' => $sum];
    }
}
```

### 2. Set Up and Run the Server

[](#2-set-up-and-run-the-server)

Next, configure and run your WebSocket server:

```
use webnarmin\AmphpWS\Configurator;
use webnarmin\AmphpWS\Simple\SimpleAuthenticator;
use webnarmin\Cryptor\Cryptor;

$config = [
    'websocket' => ['host' => '127.0.0.1', 'port' => 1337],
    'allow_origins' => ['http://127.0.0.1:8000', 'http://localhost:8000'],
];
$configurator = new Configurator($config);
$cryptor = new Cryptor('your-private-key');
$authenticator = new SimpleAuthenticator('control-http-auth-token', $cryptor);

$server = new MyWebSocketServer($configurator, $authenticator);
$server->run();
```

### Note on `SimpleAuthenticator` and `SimpleWebsocketUser`

[](#note-on-simpleauthenticator-and-simplewebsocketuser)

The classes `SimpleAuthenticator` and `SimpleWebsocketUser` are provided as basic examples. They cover essential functionalities but can be extended or replaced with custom implementations to fit specific needs.

Usage
-----

[](#usage)

### Server-side Setup

[](#server-side-setup)

To create a custom WebSocket server, extend the `WebSocketServer` class and implement your desired message handlers:

```
class MyWebSocketServer extends WebSocketServer
{
    protected function handleEcho(WebsocketUser $user, array $payload): array
    {
        return ['message' => 'Echo: ' . $payload['message']];
    }

    protected function handleSum(WebsocketUser $user, array $payload): array
    {
        $numbers = $payload['numbers'] ?? [];
        $sum = array_sum($numbers);
        return ['result' => $sum];
    }
}
```

### Client-side Usage

[](#client-side-usage)

Connect to the WebSocket server from your client-side JavaScript:

```
const socket = new WebSocket('ws://127.0.0.1:1337/ws?token=WEBSOCKET_TOKEN&publicKey=WEBSOCKET_PUBLIC_KEY');

socket.onopen = () => console.log('Connected to server');
socket.onmessage = (event) => console.log('Received:', event.data);

socket.send(JSON.stringify({ action: 'echo', payload: { message: 'Hello, WebSocket!' }}));
```

#### Token and Public Key

[](#token-and-public-key)

Generate the token and public key on the server side:

```
use webnarmin\Cryptor\Cryptor;

$cryptor = new Cryptor('websocket-private-key');
$publicKey = 'websocket-public-key';

$userId = time(); // Or any unique user identifier
$websocketToken = $cryptor->encrypt($userId, $publicKey);
```

Pass these values to your client-side code for connection.

### Broadcasting from CLI

[](#broadcasting-from-cli)

Create a PHP script to broadcast messages from the command line:

```
