PHPackages                             erfanvahabpour/laravel-swoole-ws - 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. erfanvahabpour/laravel-swoole-ws

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

erfanvahabpour/laravel-swoole-ws
================================

Laravel WebSocket server built on Swoole/OpenSwoole with routing, command protocols, scoped connections, channels, and Redis/Table-backed connection stores.

v0.1.5(4mo ago)131MITPHPPHP ^8.2CI passing

Since Dec 18Pushed 4mo agoCompare

[ Source](https://github.com/ErfanVahabpour/laravel-swoole-ws)[ Packagist](https://packagist.org/packages/erfanvahabpour/laravel-swoole-ws)[ RSS](/packages/erfanvahabpour-laravel-swoole-ws/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (4)Versions (7)Used By (0)

🔌⚡ Laravel Swoole WebSocket (laravel-swoole-ws)
===============================================

[](#-laravel-swoole-websocket-laravel-swoole-ws)

A **high-performance WebSocket server library for Laravel** powered by **Swoole / OpenSwoole**, designed for:

- Real-time applications
- IoT / device communication
- Command-based device protocols
- Channel &amp; room broadcasting
- Scalable multi-connection state management (memory / table / Redis)

This package provides a **Laravel-native DX** while running outside the HTTP lifecycle.

> ⚠️ **Status:** Under active development APIs are stabilizing, but breaking changes may occur.

---

✨ Features (at a glance)
------------------------

[](#-features-at-a-glance)

### Core

[](#core)

- 🚀 Swoole / OpenSwoole WebSocket server
- 🔌 Laravel service provider &amp; facade
- 🧭 WebSocket routing (`WS::route`)
- 🧠 Command-based device protocol (`WS::command`, `WS::response`)
- 🌐 Handshake URL path scoping (`/pub/chat`, `/attendance`, etc.)

### Security &amp; Middleware

[](#security--middleware)

- 🔐 Middleware support (`ws.auth`, custom middleware)
- 👥 Channels &amp; presence authorization

### Messaging

[](#messaging)

- 📡 Broadcast to rooms / users
- 🧩 Scoped command routing

### State &amp; Scaling

[](#state--scaling)

- 🗃 Connection stores:

    - In-memory
    - Swoole\\Table
    - Redis (multi-server ready)

### Tooling

[](#tooling)

- ⚙️ Artisan commands (`ws:start`, `ws:stop`, `ws:reload`, `ws:list`)
- 🧪 Testbench + PHPUnit support

---

📦 Requirements
--------------

[](#-requirements)

- PHP **8.2+**
- Laravel **10+**
- **Swoole** or **OpenSwoole** extension enabled

```
php -m | grep swoole
php -m | grep openswoole
```

---

📥 Installation
--------------

[](#-installation)

```
composer require erfanvahabpour/laravel-swoole-ws
```

Laravel auto-discovery is enabled.

---

🗂 Publish Config &amp; Routes
-----------------------------

[](#-publish-config--routes)

```
php artisan vendor:publish --tag=ws-config
php artisan vendor:publish --tag=ws-routes
php artisan vendor:publish --tag=ws-channels
```

Creates:

- `config/ws.php`
- `routes/ws.php`
- `routes/ws_channels.php`

---

▶️ Starting the WebSocket Server
--------------------------------

[](#️-starting-the-websocket-server)

```
php artisan ws:start
```

```
WS server starting on 0.0.0.0:9502

```

Stop / reload:

```
php artisan ws:stop
php artisan ws:reload
```

> ℹ️ On every `ws:start`, the server clears the active connection index to prevent stale connections from appearing in `ws:list`.

---

⚙️ Artisan Commands
-------------------

[](#️-artisan-commands)

```
php artisan ws:start
php artisan ws:stop
php artisan ws:reload
php artisan ws:list
```

### `ws:list`

[](#wslist)

Lists active WebSocket connections.

Example:

```
+---+----+-------------+-----------+------------+
| # | FD | Scope       | User      | Connected  |
+---+----+-------------+-----------+------------+
| 1 | 12 | /pub/chat   | guest     | 2m 14s     |
| 2 | 18 | /attendance| user#42   | 12m 03s    |
+---+----+-------------+-----------+------------+

```

Options:

```
php artisan ws:list --count
php artisan ws:list --json
```

> ℹ️ With **Swoole\\Table**, `ws:list` reflects only the current WS process. Use **Redis** for cross-process visibility.

---

🔁 WebSocket Protocols Supported
-------------------------------

[](#-websocket-protocols-supported)

This library supports **two protocols simultaneously**.

---

1️⃣ Legacy Route Protocol (`WS::route`)
---------------------------------------

[](#1️⃣-legacy-route-protocol-wsroute)

### Client → Server

[](#client--server)

```
{
  "path": "/chat",
  "action": "send",
  "data": { "text": "hello" },
  "meta": {}
}
```

### Route

[](#route)

```
WS::route('/chat', 'send', function ($ctx, $data) {
    return ['ok' => true];
});
```

---

2️⃣ Command / Device Protocol (`WS::command`)
---------------------------------------------

[](#2️⃣-command--device-protocol-wscommand)

Designed for **IoT / terminal / attendance devices**.

### Client → Server

[](#client--server-1)

```
{
  "cmd": "reg",
  "sn": "ABC123",
  "version": "1.0"
}
```

### Server → Client

[](#server--client)

```
{
  "ret": "reg",
  "result": true,
  "cloudtime": "2025-01-01 12:00:00"
}
```

---

🌐 Handshake Path Scoping
------------------------

[](#-handshake-path-scoping)

Devices can connect using different URLs:

```
ws://127.0.0.1:9502/pub/chat
ws://127.0.0.1:9502/attendance

```

Each path becomes a **routing scope**, allowing the same command names with different logic.

---

🧭 Scoped Command Routing
------------------------

[](#-scoped-command-routing)

```
WS::scope('/pub/chat')->command('reg', fn ($ctx, $payload) => ['pong' => true]);

WS::scope('/attendance')->command('reg', function ($ctx, $payload) {
    return [
        'device' => 'attendance',
        'sn' => $payload['sn'] ?? null,
    ];
});
```

---

🔄 Automatic Replies
-------------------

[](#-automatic-replies)

Returning an array automatically sends:

```
{ "ret": "", "result": true, ... }
```

Manual reply:

```
$ctx->replyRet('reg', true, ['cloudtime' => now()]);
```

---

🔌 Connection Lifecycle Helpers
------------------------------

[](#-connection-lifecycle-helpers)

```
$ctx->isEstablished();
$ctx->disconnect();
$ctx->disconnectAndForget();
```

Use `disconnectAndForget()` for:

- kicking users
- invalid devices
- admin disconnects

---

🔐 Middleware &amp; Authentication
---------------------------------

[](#-middleware--authentication)

- Built-in: `ws.auth`
- Handshake token: `?token=TOKEN`
- Message token: `{ "meta": { "auth": "TOKEN" } }`

Custom resolver:

```
config()->set('ws.auth.resolver', fn ($token) => (object)['id' => 1]);
```

---

📡 Channels &amp; Presence
-------------------------

[](#-channels--presence)

```
WS::channel('private-chat.{id}', fn ($user, $id) => true);
```

---

🗃 Connection Stores
-------------------

[](#-connection-stores)

- `memory` – simple, single worker
- `table` – fast shared memory
- `redis` – recommended for scaling &amp; CLI introspection

---

🧪 Testing &amp; CI
------------------

[](#-testing--ci)

```
vendor/bin/phpunit
```

- PHP 8.2 / 8.3
- PHPUnit
- GitHub Actions

---

🗺 Roadmap
---------

[](#-roadmap)

- WebSocket routing
- Command protocol
- Scoped connections
- Presence broadcasting
- Rate limiting
- Metrics endpoint
- Binary protocol support

---

License
-------

[](#license)

MIT © Erfan Vahabpour

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance76

Regular maintenance activity

Popularity9

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

Every ~3 days

Total

6

Last Release

128d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/139115035?v=4)[Erfan Vahabpour](/maintainers/ErfanVahabpour)[@ErfanVahabpour](https://github.com/ErfanVahabpour)

---

Top Contributors

[![ErfanVahabpour](https://avatars.githubusercontent.com/u/139115035?v=4)](https://github.com/ErfanVahabpour "ErfanVahabpour (39 commits)")

---

Tags

device-protocolevent-driveniotlaravelopenswoolephprealtimeredisswoolewebsocketphplaravelwebsocketredisswoolerealtimedeviceiotopenswoole

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/erfanvahabpour-laravel-swoole-ws/health.svg)

```
[![Health](https://phpackages.com/badges/erfanvahabpour-laravel-swoole-ws/health.svg)](https://phpackages.com/packages/erfanvahabpour-laravel-swoole-ws)
```

###  Alternatives

[basement-chat/basement-chat

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

4983.9k](/packages/basement-chat-basement-chat)[huang-yi/shadowfax

Run Laravel on Swoole.

3511.7k](/packages/huang-yi-shadowfax)[vinelab/minion

A Simple WAMP (Web Application Messaging Protocol) server and command line tool

1276.4k](/packages/vinelab-minion)[swoole-bundle/swoole-bundle

Open/Swoole Symfony Bundle

6650.4k](/packages/swoole-bundle-swoole-bundle)[sockeon/sockeon

Framework-agnostic PHP WebSocket and HTTP server library with attribute-based routing and support for namespaces and rooms.

291.3k2](/packages/sockeon-sockeon)[swoft/websocket-server

swoft websocket server component

16134.1k5](/packages/swoft-websocket-server)

PHPackages © 2026

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