Created
April 3, 2017 20:39
-
-
Save cboden/7ee2257f0affe4bac70705e379bb3e38 to your computer and use it in GitHub Desktop.
Connect to a WS server forward msgs to self WS server
This file contains hidden or 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 | |
use Ratchet\ConnectionInterface; | |
require __DIR__ . '/vendor/autoload.php'; | |
class Proxy implements \Ratchet\MessageComponentInterface { | |
private $clients; | |
public function __construct() { | |
$this->clients = new \SplObjectStorage; | |
} | |
public function onOpen(ConnectionInterface $conn) { | |
$this->clients->attach($conn); | |
} | |
public function onMessage(ConnectionInterface $from, $msg) { | |
} | |
public function onClose(ConnectionInterface $conn) { | |
$this->clients->detach($conn); | |
} | |
public function onError(ConnectionInterface $conn, \Exception $e) { | |
} | |
public function push($msg) { | |
echo "Sending `{$msg}` to clients\n"; | |
foreach($this->clients as $client) { | |
$client->send($msg); | |
} | |
} | |
} | |
$loop = React\EventLoop\Factory::create(); | |
$connector = new Ratchet\Client\Connector($loop); | |
$proxy = new Proxy; | |
$connector('ws://socketo.me/chat', ['wamp'], ['Origin' => 'http://socketo.me']) | |
->then(function(Ratchet\Client\WebSocket $conn) use ($proxy) { | |
$conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn, $proxy) { | |
$proxy->push($msg); | |
}); | |
$conn->send('[5,"room-573b3b01d0b12"]'); | |
}, function(\Exception $e) use ($loop) { | |
echo "Could not connect: {$e->getMessage()}\n"; | |
$loop->stop(); | |
}); | |
$webSock = new React\Socket\Server($loop); | |
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect | |
$webServer = new Ratchet\Server\IoServer( | |
new Ratchet\Http\HttpServer( | |
new Ratchet\WebSocket\WsServer( | |
$proxy | |
) | |
), | |
$webSock | |
); | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your tutorials, they are very educative. God bless you