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

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

brash/websocket
===============

A Websocket implementation using ReactPHP

v1.0.0(1y ago)0901MITPHPPHP &gt;=8.3.0

Since Dec 27Pushed 1y agoCompare

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

READMEChangelog (1)Dependencies (14)Versions (2)Used By (1)

Brash/Websocket
===============

[](#brashwebsocket)

[![example workflow](https://github.com/BrashPHP/websocket/actions/workflows/tests.yml/badge.svg)](https://github.com/BrashPHP/websocket/actions/workflows/tests.yml/badge.svg)

PHP has a number of REALLY good libraries to handle the WebSocket Protocol out there - some of which I solely based this project upon. This package/library/project offers a number of features present in those, using ReactPHP as its asyncronous handler. I developed this project as a way to understand in depth how the protocol worked in real life and how I could create something more lower-level with it without the need to use something more lower-level or too much abstracted, such as Socket.io and others. Build your application using small, reusable and atomic components if you want or simply drop a single handler for incoming data, this library will handle compression, deflation and connection for you.

---

- [IMPORTANT](#important)
- [Install](#install)
- [How to](#how-to)
- [Requirements](#requirements)
- [Configuration](#configuration)
    - [Connection Object)](#connection-object)
    - [WebSocket Secured (alias WSS)](#websocket-secured-alias-wss)
- [Features Checklist + Challenges](#features-checklist-challenges)
- [Understanding The Protocol](#understanding-the-protocol)
- [Based on](#based-on)

IMPORTANT
---------

[](#important)

This library is server-side only. I did not have interest in implementing client code, but feel free to do it if you are into that ;)

Install
-------

[](#install)

```
composer require brash/websocket
```

How to
------

[](#how-to)

Quick start:

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

$server = new \Brash\Websocket\WsServer(host: '0.0.0.0', port: 1337);

$server->setConnectionHandler(
    connectionHandlerInterface: new class extends \Brash\Websocket\Message\Protocols\AbstractTextMessageHandler {

    private array $connections;

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

    // Optional, as with on onDisconnect, onError
    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);
        }
    }
    }
);
$server->start();
```

Whether using this library as a standalone solution or on top of other ReactPHP libraries (e.g, HTTP Server), the important piece is the declaration of a handler to execute real-time busineess logic.

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

[](#requirements)

- PHP 8.3^

Configuration
-------------

[](#configuration)

You can create a configuration object using the constructor of from the static method `createFromArray`.

```
$configArray = [
    'timeout' => 5, // In seconds
    'maxPayloadSize' => 524288, //(0.5MiB)
    'maxMessagesBuffering' => 100, // 5mb in messages
    'writeMasked' => false,
    'prod' => true,
    'ssl' => false,
    'certFile' => '',
    'passphrase' => '',
    'sslContextOptions' => [],
];

$config = \Brash\Websocket\Config\Config::createFromArray($configArray);

// OR
$config = new \Brash\Websocket\Config\Config(
    // DEFAULTS: int $timeout = self::MESSAGE_TIMEOUT_IN_SECONDS,
    // DEFAULTS: int $maxPayloadSize = self::MAX_PAYLOAD_SIZE,
    // DEFAULTS: int $maxMessagesBuffering = self::MAX_MESSAGES_BUFFERING,
    // DEFAULTS: bool $writeMasked = false,
    // DEFAULTS: bool $prod = true,
    // DEFAULTS: ?\Brash\Websocket\Config\SslConfig $sslConfig = null
);

$server = new \Brash\Websocket\WsServer(host: '0.0.0.0', port: 1337, $config);
```

### Connection Object

[](#connection-object)

The `Connection` object has the following methods you can use:

- `getIp(): string`
- `getLogger(): LoggerInterface`
- `getSocketWriter(): MessageWriter`
- `write(string|Frame $frame, FrameTypeEnum $frameTypeEnum): void`
- `writeText(string|Frame $frame): void`
- `writeBinary(string|Frame $frame): void`

### WebSocket Secured (alias WSS)

[](#websocket-secured-alias-wss)

In new apps you often use https. So you should use wss with WebSockets to secure data exchange. Woketo supports wss out of the box, you just need to add the related options (`ssl` and `certFile`).

You should instanciate woketo like this:

```
$server = new \Brash\Websocket\WsServer(9001, '127.0.0.1',
    new Config(
        ...[
            'ssl' => true,
            'certFile' => 'path/to/certificate/cert.pem',
            'sslContextOptions' => [
                'verify_peer' => false,
                'allow_self_signed' => true
            ]
        ]
    )
);
```

> Why is there only one cert file required while I have 2 files (cert and private key) ?

PHP uses a PEM formatted certificate that contains the certificate *and* the private key.

Here is a way to generate your PEM formatted certificate for a local usage:

```
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout acme.key -out acme.crt
cat acme.key > acme.pem
cat acme.crt >> acme.pem
```

Features Checklist + Challenges
-------------------------------

[](#features-checklist--challenges)

- Web Socket Server
    - Receiving data
        - Establishes handshake connections according to the Web Socket protocol
        - Receives masked data payloads
        - Receives TEXT and BINARY frames
        - Decodes 7-bits long data payloads
        - Decodes 16-bits long data payloads
        - Decodes 64-bits long data payloads
        - Uses permessage-deflate with zlib to handle inflate out-of-the-box.
        - WSS Support (WebSocket over SSL).
    - Replying (see example/vue-client/SocketChat)
        - Builds data frames according to the Web Socket protocol
        - Sends 7-bits long unmasked data payloads
        - Sends 16-bits long unmasked data payloads
        - Sends 64-bits long unmasked data payloads
        - Responds deflate messages with zlib out-of-the-box.

Understanding The Protocol
--------------------------

[](#understanding-the-protocol)

This project relies on heavy documentation, tests and other repositories. You can read more on:

- [MDN](https://developer.mozilla.org/pt-BR/docs/Web/API/WebSockets_API/Writing_WebSocket_servers)
- [Erick Wendel's Blog](https://blog.erickwendel.com.br/implementing-the-websocket-protocol-from-scratch-using-nodejs#heading-unmasking-the-data)
    - I could spend a lot of time explaining every single detail about this implementation, but luckly someone else has made it before I would :D
- [Masking, Fragments and Stuff](https://www.openmymind.net/WebSocket-Framing-Masking-Fragmentation-and-More/)
- [MDN](https://developer.mozilla.org/pt-BR/docs/Web/API/WebSockets_API/Writing_WebSocket_servers)

Based on
--------

[](#based-on)

- [HEAVILY BASED ON Woketo](https://github.com/Nekland/Woketo/)
- [Websocket Client and Server for PHP](https://github.com/sirn-se/websocket-php/tree/v3.1-main)
- [AMP Websocket Server](https://github.com/amphp/websocket-server/)
- [Ratchet](https://github.com/ratchetphp/Ratchet)

Versioning
----------

[](#versioning)

This package follows the semver semantic versioning specification.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance40

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community8

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

508d 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

asyncdeflatephpreactphpserverwebsocketwebsocket-serverphppackagewebsocket

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[openswoole/core

Openswoole core library

181.1M32](/packages/openswoole-core)[valga/fbns-react

A PHP client for the FBNS built on top of ReactPHP

15751.3k19](/packages/valga-fbns-react)[basement-chat/basement-chat

Add a real-time chat widget to your Laravel application.

4983.9k](/packages/basement-chat-basement-chat)[hyperf/websocket-server

A websocket server library for Hyperf.

12488.7k25](/packages/hyperf-websocket-server)[hemiframe/php-websocket

PHP WebSocket server and client library

4911.0k](/packages/hemiframe-php-websocket)

PHPackages © 2026

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