brash/websocket-middleware 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

brash/websocket-middleware

Composer 安装命令:

composer require brash/websocket-middleware

包简介

A WebSocket Middleware to be used with an HTTP Server

README 文档

README

WebSocket PHP

WebSocket Middleware for react/http

This package provides a PHP React/HTTP WebSocket Middleware.

Requires PHP 8.3+

This library provides a WebSocket message broadcasting solution using the ReactPHP library. It demonstrates how to handle incoming text messages, broadcast messages to other connected clients, and log connection details.

Requirements

Installation

  1. Install the dependencies via Composer:

    composer install
  2. Ensure the autoloader is included:

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

Usage

Starting the Server

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

php your_script.php [host:port]

Key Components

AbstractTextMessageHandler

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

MiddlewareFactory

Creates the middleware required for handling WebSocket connections.

React\Http\HttpServer

Handles HTTP requests and integrates WebSocket middleware.

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

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

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

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

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

Contributions

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

Acknowledgments

Enjoy using the WebSocket Message Broadcasting Library!

brash/websocket-middleware 适用场景与选型建议

brash/websocket-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「package」 「php」 「Skeleton」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 brash/websocket-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 brash/websocket-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 brash/websocket-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 11
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-08