thenlabs/socket-server

v1.1.7 2022-04-19 13:38 UTC

This package is auto-updated.

Last update: 2024-09-19 20:08:25 UTC


README

一个用于使用PHP创建异步网络应用的实用库。

如果您喜欢这个项目,请给我们一个⭐。

特性。

  • 异步连接。
  • 多种配置选项。
  • 事件系统以实现应用逻辑。
  • 日志支持。

安装。

$ composer require thenlabs/socket-server

用法。

以下代码展示了一个基本的网络应用,该应用可以接受多个连接并将每个传入的消息转发给其他所有连接。

该应用可以在tests/Functional/hub.php文件中找到。要测试它,您可以运行php tests/Functional/hub.php

可以看到,SocketServer类提供了处理不同连接状态所需的事件。

查看SocketServer API以了解所有可能性。

<?php
/**
 * What this program does is accept multiple connections and forward
 * each incoming message to the rest of the connections.
 */

require_once __DIR__.'/../../bootstrap.php';

use ThenLabs\SocketServer\Event\ConnectionEvent;
use ThenLabs\SocketServer\Event\DataEvent;
use ThenLabs\SocketServer\Event\DisconnectionEvent;
use ThenLabs\SocketServer\SocketServer;

class HubServer extends SocketServer
{
    protected $connections = [];

    public function onConnection(ConnectionEvent $event): void
    {
        foreach ($this->connections as $connection) {
            $connection->writeLine("New connection.");
        }

        $this->connections[] = $event->getConnection();
    }

    public function onData(DataEvent $event): void
    {
        $data = $event->getData();

        switch ($data) {
            case 'exit':
                $event->getConnection()->close();
                break;

            case 'stop':
                $event->getServer()->stop();
                break;

            default:
                foreach ($this->connections as $connection) {
                    if ($connection != $event->getConnection()) {
                        $connection->writeLine($data);
                    }
                }
                break;
        }
    }

    public function onDisconnection(DisconnectionEvent $event): void
    {
        foreach ($this->connections as $id => $connection) {
            if ($connection == $event->getConnection()) {
                unset($this->connections[$id]);
                break;
            }
        }
    }
}

$server = new HubServer(['socket' => $argv[1] ?? 'tcp://127.0.0.1:9000']);
$server->start();

上述示例的工作原理如下

开发。

运行测试。

要运行测试,请运行以下命令

$ ./vendor/bin/pyramidal