PHPackages                             tourze/workerman-connection-pipe - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. tourze/workerman-connection-pipe

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tourze/workerman-connection-pipe
================================

连接间转发，支持TCP和UDP

0.0.4(6mo ago)05744MITPHPCI passing

Since Apr 1Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/workerman-connection-pipe)[ Packagist](https://packagist.org/packages/tourze/workerman-connection-pipe)[ RSS](/packages/tourze-workerman-connection-pipe/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (11)Versions (5)Used By (4)

Workerman Connection Pipe
=========================

[](#workerman-connection-pipe)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/956449e9139d49a05bd470433af14d1f5c50e57e041317ee33e62b7e782bbca1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f776f726b65726d616e2d636f6e6e656374696f6e2d706970652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/workerman-connection-pipe)[![Total Downloads](https://camo.githubusercontent.com/d0c4f9c838a2e4138be2e0e3c1c9bb427c9b7dba3574214bd17d098a1bdc717c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f776f726b65726d616e2d636f6e6e656374696f6e2d706970652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/workerman-connection-pipe)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)](https://php.net/)[![Coverage Status](https://camo.githubusercontent.com/b3545ae1bcdb4ea486f71f87b43001e82dd21933bc8035d44601706c851265da/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e2e737667)](https://github.com/tourze/workerman-connection-pipe)

A high-performance, highly customizable connection forwarding framework based on Workerman, supporting data transmission and protocol conversion between TCP and UDP connections.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
    - [Configuration](#configuration)
    - [TCP to TCP Proxy Example](#tcp-to-tcp-proxy-example)
    - [UDP to UDP Forwarding Example](#udp-to-udp-forwarding-example)
- [Listening to Events](#listening-to-events)
- [Custom Data Processing](#custom-data-processing)
- [Detailed Workflows](#detailed-workflows)
- [Advanced Configuration](#advanced-configuration)
    - [Setting Buffer Size](#setting-buffer-size)
    - [Enabling Encrypted Transport](#enabling-encrypted-transport)
- [Performance Optimization Tips](#performance-optimization-tips)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [Changelog](#changelog)
- [License](#license)

Features
--------

[](#features)

- **Multi-protocol Support**

    - TCP → TCP: Transparent TCP proxying, load balancing, and reverse proxying
    - TCP → UDP: Access UDP services from TCP clients, such as DNS proxying
    - UDP → TCP: Access TCP services from UDP clients, such as game server frontend
    - UDP → UDP: UDP relay, stream forwarding, with full-cone NAT support
- **Advanced Connection Management**

    - Automatic connection lifecycle and resource release management
    - Smart buffer control to prevent memory overflow
    - Timeout cleanup mechanism that automatically releases inactive connections
- **Powerful Extension Functions**

    - Complete event system for monitoring all forwarding events
    - Flexible logging interface for recording detailed connection and transmission information
    - Custom data processing logic for protocol conversion and content modification

Installation
------------

[](#installation)

```
composer require tourze/workerman-connection-pipe
```

Quick Start
-----------

[](#quick-start)

### Configuration

[](#configuration)

First, configure the dependency container, setting up the logger and event dispatcher:

```
use Tourze\Workerman\ConnectionPipe\Container;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Symfony\Component\EventDispatcher\EventDispatcher;

// Configure logging system
$logger = new Logger('pipe');
$logger->pushHandler(new StreamHandler('path/to/your/app.log', Logger::DEBUG));
Container::$logger = $logger;

// Configure event dispatcher
$eventDispatcher = new EventDispatcher();
Container::$eventDispatcher = $eventDispatcher;
```

### TCP to TCP Proxy Example

[](#tcp-to-tcp-proxy-example)

Create a simple TCP proxy that forwards traffic from local port 8443 to a remote server:

```
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
use Tourze\Workerman\ConnectionPipe\PipeFactory;

// Create local listening service
$worker = new Worker('tcp://0.0.0.0:8443');

$worker->onConnect = function(TcpConnection $connection) {
    // Create connection to target server
    $targetConnection = new AsyncTcpConnection('tcp://example.com:443');
    $targetConnection->connect();

    // Create and start pipe from source to target
    $forwardPipe = PipeFactory::createTcpToTcp($connection, $targetConnection);
    $forwardPipe->pipe();

    // Create and start pipe from target to source
    $backwardPipe = PipeFactory::createTcpToTcp($targetConnection, $connection);
    $backwardPipe->pipe();

    // Save pipe references for later cleanup
    $connection->pipeTo = $forwardPipe;
    $connection->pipeFrom = $backwardPipe;

    // Set cleanup logic when source connection closes
    $connection->onClose = function() use ($connection) {
        if (isset($connection->pipeTo)) {
            $connection->pipeTo->unpipe();
        }
        if (isset($connection->pipeFrom)) {
            $connection->pipeFrom->unpipe();
        }
    };
};

Worker::runAll();
```

### UDP to UDP Forwarding Example

[](#udp-to-udp-forwarding-example)

Create a UDP forwarding service that forwards UDP traffic from local port 8053 to Google's DNS server:

```
use Workerman\Worker;
use Workerman\Connection\AsyncUdpConnection;
use Tourze\Workerman\ConnectionPipe\PipeFactory;

// Create UDP source server
$sourceWorker = new Worker('udp://0.0.0.0:8053');

$sourceWorker->onWorkerStart = function($worker) {
    // Create UDP connection to target DNS server
    $targetConnection = new AsyncUdpConnection('udp://8.8.8.8:53');

    $targetConnection->onConnect = function($connection) use ($worker) {
        echo "Connected to target UDP server\n";
        // Store the target connection
        $worker->targetConnection = $connection;

        // Get UDP connection objects
        $sourceConnection = $worker->getMainSocket();

        // Create UDP to UDP pipe
        $pipe = PipeFactory::createUdpToUdp($sourceConnection, $connection);

        // Store pipe reference
        $worker->pipe = $pipe;

        // Start the pipe
        $pipe->pipe();
    };

    $targetConnection->connect();
};

$sourceWorker->onMessage = function($connection, $data, $sourceAddress, $sourcePort) {
    $worker = $connection->worker;

    // Check if target connection is available
    if (!isset($worker->pipe)) {
        return;
    }

    // Forward the data with source address information
    $worker->pipe->forward($data, $sourceAddress, $sourcePort);
};

Worker::runAll();
```

Listening to Events
-------------------

[](#listening-to-events)

You can listen to data forwarding related events for custom processing:

```
use Tourze\Workerman\ConnectionPipe\Event\DataForwardedEvent;
use Tourze\Workerman\ConnectionPipe\Event\ForwardFailedEvent;
use Tourze\Workerman\ConnectionPipe\Container;

// Listen for successful data forwarding events
Container::$eventDispatcher->addListener(
    DataForwardedEvent::class,
    function(DataForwardedEvent $event) {
        $pipe = $event->getPipe();
        $data = $event->getData();
        $sourceProtocol = $event->getSourceProtocol();
        $targetProtocol = $event->getTargetProtocol();
        $context = $event->getContext();

        // Process successfully forwarded data, e.g., statistics or logging
        echo "Forwarded " . strlen($data) . " bytes from {$sourceProtocol} to {$targetProtocol}\n";
    }
);

// Listen for data forwarding failure events
Container::$eventDispatcher->addListener(
    ForwardFailedEvent::class,
    function(ForwardFailedEvent $event) {
        $errorMessage = $event->getErrorMessage();

        // Handle forwarding failure, e.g., warning or retry
        echo "Forwarding failed: {$errorMessage}\n";
    }
);
```

Custom Data Processing
----------------------

[](#custom-data-processing)

If you need to modify or process data during forwarding, you can extend existing pipe classes and override relevant methods:

```
use Tourze\Workerman\ConnectionPipe\Pipe\TcpToTcpPipe;

class EncryptedTcpPipe extends TcpToTcpPipe
{
    public function forward(string $data, string $sourceAddress = '', int $sourcePort = 0): bool
    {
        // Encrypt or process data before forwarding
        $processedData = $this->encryptData($data);

        // Call parent method to complete actual forwarding
        return parent::forward($processedData, $sourceAddress, $sourcePort);
    }

    protected function encryptData(string $data): string
    {
        // Implement your data encryption or processing logic
        return $data; // No actual processing in this example
    }
}

// Use custom pipe class
$pipe = new EncryptedTcpPipe();
$pipe->setSource($sourceConnection);
$pipe->setTarget($targetConnection);
$pipe->pipe();
```

Detailed Workflows
------------------

[](#detailed-workflows)

For detailed workflows of each connection combination, see the [workflows](./workflows) directory:

- [TCP to TCP Forwarding Workflow](./workflows/tcp_to_tcp_workflow.md)
- [TCP to UDP Forwarding Workflow](./workflows/tcp_to_udp_workflow.md)
- [UDP to TCP Forwarding Workflow](./workflows/udp_to_tcp_workflow.md)
- [UDP to UDP Forwarding Workflow](./workflows/udp_to_udp_workflow.md)

Advanced Configuration
----------------------

[](#advanced-configuration)

### Setting Buffer Size

[](#setting-buffer-size)

For high-traffic applications, you can adjust the buffer size of TCP connections:

```
use Workerman\Connection\TcpConnection;

// Set global maximum send buffer size to 10MB
TcpConnection::$defaultMaxSendBufferSize = 10 * 1024 * 1024;

// Set buffer size for a single connection
$targetConnection->maxSendBufferSize = 5 * 1024 * 1024;
```

### Enabling Encrypted Transport

[](#enabling-encrypted-transport)

You can enable SSL/TLS encryption on TCP connections:

```
$targetConnection = new AsyncTcpConnection('tcp://example.com:443');

// Enable SSL
$targetConnection->transport = 'ssl';

$targetConnection->connect();
```

Performance Optimization Tips
-----------------------------

[](#performance-optimization-tips)

1. **Connection Reuse**: For frequently established connections, consider implementing a connection pool to reduce connection establishment overhead.
2. **Multi-process Mode**: On multi-core servers, allocate an appropriate number of Worker processes:

    ```
    $worker->count = 4; // Adjust based on CPU cores and load
    ```
3. **Memory Optimization**: For long-running applications, periodically check memory usage to prevent memory leaks.
4. **Timeout Settings**: Set appropriate timeout values for different application scenarios to ensure resources are released in a timely manner.

Troubleshooting
---------------

[](#troubleshooting)

1. **Connection Cannot Be Established**: Check network connectivity, firewall settings, and whether the target server is reachable.
2. **Data Forwarding Failure**: Ensure pipes are correctly created and started, check error messages in event listeners.
3. **High Memory Usage**: Check if connections are properly closed and NAT mappings are periodically cleaned up.
4. **Unstable UDP Communication**: UDP does not have connection state, ensure proper handling of packet loss and out-of-order situations.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for details on what has changed in each version.

License
-------

[](#license)

This project is licensed under the [MIT License](LICENSE).

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance76

Regular maintenance activity

Popularity15

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 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 ~71 days

Total

4

Last Release

188d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

---

Tags

connectionpipeworkerman

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-workerman-connection-pipe/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-workerman-connection-pipe/health.svg)](https://phpackages.com/packages/tourze-workerman-connection-pipe)
```

###  Alternatives

[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[phpro/soap-client

A general purpose SoapClient library

8885.6M46](/packages/phpro-soap-client)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k17](/packages/civicrm-civicrm-core)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k134](/packages/symfony-ai-platform)

PHPackages © 2026

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