Created
February 19, 2020 16:37
-
-
Save WyriHaximus/f505e61fe89519a16ca68f2e055d2a04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
use React\EventLoop\Factory; | |
use React\EventLoop\LoopInterface; | |
use React\Socket\ConnectionInterface; | |
use React\Socket\Connector; | |
use React\Socket\Server; | |
use React\Stream\Util; | |
require 'vendor/autoload.php'; | |
function createProxy(LoopInterface $loop, Connector $connector, int $port, string $to): Server | |
{ | |
$uri = 'tcp://0.0.0.0:' . $port; | |
echo 'Listening on: ', $uri, PHP_EOL; | |
$proxy = new Server($uri, $loop); | |
$proxy->on('connection', function (ConnectionInterface $connection) use ($loop, $to, $connector) { | |
$connection->pause(); | |
$uri = 'tcp://' . $to; | |
echo 'Opening connection to: ', $uri, PHP_EOL; | |
$connector->connect($uri)->then(function (ConnectionInterface $service) use ($connection) { | |
echo 'Connected!', PHP_EOL; | |
Util::pipe($connection, $service, ['end' => true]); | |
Util::pipe($service, $connection, ['end' => true]); | |
$connection->resume(); | |
}, function (Throwable $throwable) { | |
echo $throwable, PHP_EOL; | |
}); | |
}); | |
return $proxy; | |
} | |
$loop = Factory::create(); | |
$connector = new Connector($loop); | |
$proxies = []; | |
$signalHandler = function () use (&$signalHandler, &$proxies, $loop) { | |
$loop->removeSignal(SIGINT, $signalHandler); | |
$loop->removeSignal(SIGTERM, $signalHandler); | |
foreach ($proxies as $proxy) { | |
$proxy->close(); | |
} | |
}; | |
$loop->addSignal(SIGINT, $signalHandler); | |
$loop->addSignal(SIGTERM, $signalHandler); | |
foreach (file('/etc/proxy/routes') as $route) { | |
[$port, $to] = explode('=>', $route); | |
$proxies[] = createProxy($loop, $connector, (int)$port, $to); | |
} | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment