phprivoxy/core

处理TCP和HTTP连接的核心库。

v0.10.4 2024-07-02 13:51 UTC

This package is auto-updated.

Last update: 2024-09-02 14:09:25 UTC


README

处理TCP连接的核心库。

这个基于Workerman框架(https://github.com/walkor/workerman)的PHP包,主要用于创建自定义代理服务器。

要求

  • PHP >= 8.1

安装

使用composer(推荐)

composer create phprivoxy/core

简单的TCP服务器示例

namespace PHPrivoxy\Core;

use Workerman\Connection\TcpConnection;

class HelloWorld implements PHPrivoxy\Core\Tcp\TcpHandlerInterface
{
    public function handle(TcpConnection $connection, ?ConnectionParameters $connectionParameters = null): void
    {
        $connection->send("HTTP/1.1 200 OK\r\ncontent-type: text/html;charset=UTF8\r\n\r\n" . 'Hello, world!');
        $connection->close();
    }
}

$handler = new HelloWorld();
new TcpServer($handler, 1, 8080, '0.0.0.0');

您还可以在"tests"目录中找到此示例。

只需运行它

php tests/tcp_server.php start

将浏览器配置为通过IP地址为127.0.0.1,端口号为8080的代理服务器工作。

尝试以HTTP协议打开任何网站。例如,尝试打开https://php.ac.cnhttp://google.comhttp://microsoft.com

尝试打开http://not-existing-site/ - 它将工作!:-)

简单的HTTP服务器示例

namespace PHPrivoxy\Core;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Workerman\Connection\TcpConnection;

class Psr7HelloWorld implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new Workerman\Psr7\Response(200, ['content-type' => 'text/html'], 'Hello, world!');
    }
}

class ResponseHandler implements PHPrivoxy\Core\Http\ResponseHandlerInterface
{
    public function handle(ResponseInterface $response, TcpConnection $connection): void
    {
        $connection->send($response);
        $connection->close();
    }
}

$requestHandler = new Psr7HelloWorld();
$responseHandler = new ResponseHandler();
new HttpServer($requestHandler, $responseHandler, 1, 8080, '0.0.0.0');

您还可以在"tests"目录中找到此示例。

只需运行它

php tests/http_server.php start

### License
MIT License See [LICENSE](LICENSE)