webnarmin/amphp-websocket-server

具有HTTP控制和认证功能的WebSocket服务器

v1.0.0 2024-06-29 15:44 UTC

This package is auto-updated.

Last update: 2024-09-30 10:17:55 UTC


README

使用Amp并发框架的PHP灵活高效的WebSocket服务器实现。这个库使开发者能够轻松创建实时、交互式的Web应用程序,提供认证、消息处理、广播等功能。它旨在可扩展和高效,非常适合高性能应用。

功能

  • 简单设置:启动时所需配置最少。
  • 认证:支持WebSocket和HTTP控制请求的认证。
  • 消息处理:自定义客户端消息的操作。
  • 广播:一次性向多个客户端发送消息。
  • 安全连接:可选的SSL/TLS支持。
  • 可扩展:易于扩展和定制。

目录

安装

通过Composer安装

composer require webnarmin/amphp-websocket-server

快速入门

1. 创建WebSocket服务器类

首先,扩展WebSocketServer类并定义你的消息处理程序

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. 设置并运行服务器

接下来,配置并运行你的WebSocket服务器

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', 'https://: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();

关于SimpleAuthenticatorSimpleWebsocketUser的说明

SimpleAuthenticatorSimpleWebsocketUser提供了一些基本示例。它们涵盖了基本功能,但可以根据特定需求扩展或替换为自定义实现。

使用

服务器端设置

要创建自定义的WebSocket服务器,扩展WebSocketServer类并实现你需要的消息处理程序

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];
    }
}

客户端使用

从客户端JavaScript连接到WebSocket服务器

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!' }}));

令牌和公钥

在服务器端生成令牌和公钥

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

将这些值传递给客户端代码以进行连接。

从CLI广播

创建一个PHP脚本来从命令行广播消息

<?php
use GuzzleHttp\Client;
use webnarmin\AmphpWS\WebsocketControlHttpClient;
use Psr\Log\NullLogger;

require '../vendor/autoload.php';

$baseUri = 'http://127.0.0.1:8080';
$authToken = 'control-http-auth-token';

// Create a Guzzle HTTP client instance
$httpClient = new Client([
    'base_uri' => $baseUri,
    'headers' => [
        'Authorization' => $authToken,
        'Content-Type' => 'application/json',
    ],
]);

$client = new WebsocketControlHttpClient($httpClient, new NullLogger());

// Send a broadcast message
$success = $client->broadcastText('Hello, everyone!');

if ($success) {
    echo "Message broadcasted successfully.";
} else {
    echo "Failed to broadcast message.";
}

// Send a targeted message
$success = $client->sendText(1, 'Hello, User 1!');

if ($success) {
    echo "Message sent to user 1 successfully.";
} else {
    echo "Failed to send message to user 1.";
}

// Send a binary broadcast message
$binaryData = file_get_contents('path/to/file');
$success = $client->broadcastBinary($binaryData);

if ($success) {
    echo "Binary data broadcasted successfully.";
} else {
    echo "Failed to broadcast binary data.";
}

// Multicast a text message
$success = $client->multicastText('Hello, selected users!', [1, 2, 3]);

if ($success) {
    echo "Multicast message sent successfully.";
} else {
    echo "Failed to send multicast message.";
}

// Multicast a binary message
$binaryData = file_get_contents('path/to/file');
$success = $client->multicastBinary($binaryData, [1, 2, 3]);

if ($success) {
    echo "Binary data multicast successfully.";
} else {
    echo "Failed to multicast binary data.";
}

从命令行运行此脚本以向所有连接的客户端广播消息。

配置

可以在创建Configurator实例时设置配置选项

$config = [
    'websocket' => [
        'host' => '127.0.0.1',
        'port' => 1337,
        'use_ssl' => false,
        'ssl_cert' => null,
        'ssl_key' => null,
    ],
    'allow_origins' => ['*'],
    'max_connections' => 1000,
    'max_connections_per_ip' => 10,
    'timeout' => 60,
];

$configurator = new Configurator($config);

贡献

欢迎贡献!请随时提交Pull Request。

许可

本项目采用MIT许可协议。