Skip to content

Instantly share code, notes, and snippets.

@cboden
Created April 3, 2017 20:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cboden/7ee2257f0affe4bac70705e379bb3e38 to your computer and use it in GitHub Desktop.
Save cboden/7ee2257f0affe4bac70705e379bb3e38 to your computer and use it in GitHub Desktop.
Connect to a WS server forward msgs to self WS server
<?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();
@JoshuaKeyz
Copy link

Thanks for your tutorials, they are very educative. God bless you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment