PHPackages                             brash/websocket-middleware - 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. brash/websocket-middleware

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

brash/websocket-middleware
==========================

 A WebSocket Middleware to be used with an HTTP Server

v1.0.0(1y ago)048MITPHPPHP ^8.3.0

Since Jan 8Pushed 1y agoCompare

[ Source](https://github.com/BrashPHP/websocket-middleware)[ Packagist](https://packagist.org/packages/brash/websocket-middleware)[ Fund](https://www.paypal.com/paypalme/enunomaduro)[ GitHub Sponsors](https://github.com/nunomaduro)[ RSS](/packages/brash-websocket-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (11)Versions (2)Used By (0)

 [![WebSocket PHP](https://raw.githubusercontent.com/BrashPHP/websocket-middleware/main/docs/image.png)](https://raw.githubusercontent.com/BrashPHP/websocket-middleware/main/docs/image.png)

---

WebSocket Middleware for react/http
===================================

[](#websocket-middleware-for-reacthttp)

This package provides a PHP React/HTTP WebSocket Middleware.

> **Requires [PHP 8.3+](https://php.net/releases/)**

This library provides a WebSocket message broadcasting solution using the [ReactPHP](https://reactphp.org/) library. It demonstrates how to handle incoming text messages, broadcast messages to other connected clients, and log connection details.

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- Composer
- [ReactPHP](https://reactphp.org/)
- [Brash\\Websocket](https://github.com/BrashPHP/websocket) library

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

[](#installation)

1. Install the dependencies via Composer:

    ```
    composer install
    ```
2. Ensure the autoloader is included:

    ```
    require_once __DIR__.'/vendor/autoload.php';
    ```

Usage
-----

[](#usage)

### Starting the Server

[](#starting-the-server)

Run the WebSocket server by executing the script in your terminal:

```
php your_script.php [host:port]
```

### Key Components

[](#key-components)

#### `AbstractTextMessageHandler`

[](#abstracttextmessagehandler)

The `AbstractTextMessageHandler` class handles WebSocket text messages. This implementation processes new connections, receives data, and broadcasts it to other connected clients.

#### `MiddlewareFactory`

[](#middlewarefactory)

Creates the middleware required for handling WebSocket connections.

#### `React\Http\HttpServer`

[](#reacthttphttpserver)

Handles HTTP requests and integrates WebSocket middleware.

### Implementation Details

[](#implementation-details)

1. **Connection Handling**

    - The server tracks all active connections in the `$connections` array.
    - When a new connection is established, it is added to the array using the `onOpen` method.
2. **Message Broadcasting**

    - When a client sends a message, it is logged using the connection’s logger.
    - The message is broadcast to all other clients, except the sender.
    - The sender receives a response that includes their IP address and the message content in uppercase.

#### Code Example

[](#code-example)

Here is the core server implementation:

```
$connectionHandlerInterface = new class extends AbstractTextMessageHandler
{
    private array $connections;

    public function __construct()
    {
        $this->connections = [];
    }

    public function onOpen(\Brash\Websocket\Connection\Connection $connection): void
    {
        $this->connections[] = $connection;
    }

    public function handleTextData(string $data, \Brash\Websocket\Connection\Connection $connection): void
    {
        $connection->getLogger()->debug('IP'.':'.$connection->getIp().PHP_EOL);
        $connection->getLogger()->debug('Data: '.$data.PHP_EOL);
        $broadcast = array_filter($this->connections, fn ($conn) => $conn !== $connection);

        foreach ($broadcast as $conn) {
            $conn->writeText($data);
        }
        $connection->writeText($connection->getIp().'says: '.strtoupper($data));
    }
};

$middleware = $factory->create($connectionHandlerInterface);

$socket = new \React\Socket\SocketServer($argv[1] ?? '0.0.0.0:1337');

$server = new HttpServer($middleware);

$server->listen($socket);

echo 'Listening on '.str_replace('tcp:', 'http:', $socket->getAddress()).PHP_EOL;
```

### Example Output

[](#example-output)

When a client connects and sends a message:

1. The server logs the IP address and message data.
2. All other connected clients receive the message.
3. The sender receives a response in uppercase:

```
Client 1 sends: Hello World
Client 2 receives: Hello World
Client 1 receives: 127.0.0.1 says: HELLO WORLD

```

### Config Options

[](#config-options)

It is optional to set a Config object in the MiddlewareFactory, but you can do it as:

```
use Brash\Websocket\Config\Config;

$factory = new MiddlewareFactory();
$factory->withConfig(new Config());
```

It is optional to set an array of paths, but this can be achieved as follows:

```
$factory = new MiddlewareFactory();
$factory->withParams([
    '/test'
]);
```

License
-------

[](#license)

This library is licensed under the MIT License. See the `LICENSE` file for more details.

Contributions
-------------

[](#contributions)

Contributions are welcome! Feel free to submit issues or pull requests on GitHub.

Acknowledgments
---------------

[](#acknowledgments)

- [ReactPHP](https://reactphp.org/)
- [Brash\\Websocket](https://github.com/your-project)

---

Enjoy using the WebSocket Message Broadcasting Library!

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance41

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

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

495d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2754bf7a9174f2abafce9571a9d87dc2e705c284aedbe227cab3e3f85c9bfb61?d=identicon)[Gabriel Berthier](/maintainers/Gabriel%20Berthier)

---

Top Contributors

[![gabrielberthier](https://avatars.githubusercontent.com/u/40048106?v=4)](https://github.com/gabrielberthier "gabrielberthier (2 commits)")

---

Tags

phppackageSkeleton

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/brash-websocket-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/brash-websocket-middleware/health.svg)](https://phpackages.com/packages/brash-websocket-middleware)
```

###  Alternatives

[huaweicloud/huaweicloud-sdk-php

Huawei Cloud SDK for PHP

1829.2k2](/packages/huaweicloud-huaweicloud-sdk-php)[openswoole/core

Openswoole core library

181.1M32](/packages/openswoole-core)[aphiria/aphiria

The Aphiria framework

1427.7k2](/packages/aphiria-aphiria)[genkgo/archive-stream

Stream a ZIP file (memory efficient) as a PSR-7 message

3063.0k](/packages/genkgo-archive-stream)

PHPackages © 2026

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