Skip to content

Instantly share code, notes, and snippets.

@igorw
Created October 6, 2012 13:41
Show Gist options
  • Save igorw/3844965 to your computer and use it in GitHub Desktop.
Save igorw/3844965 to your computer and use it in GitHub Desktop.
React Chatroulette
{
"require": {
"react/socket": "0.2.*"
}
}
<?php
// nc localhost 4000
require 'vendor/autoload.php';
function getConnectionId($conn)
{
// ugh!
static $i = 0;
if (!isset($conn->id)) {
$conn->id = ++$i;
}
return $conn->id;
}
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$waiting = null;
$socket->on('connection', function ($conn) use (&$waiting) {
printf("New connection %s\n", getConnectionId($conn));
$conn->write(sprintf("Hello %s!\n", getConnectionId($conn)));
$conn->on('end', function () {
printf("Connection %s disconnected\n", getConnectionId($conn));
});
if (null === $waiting || !$waiting->isReadable()) {
$waiting = $conn;
$conn->write("Please wait until a partner connects.\n");
return;
}
printf("Pairing up connection %s with waiting connection %s.\n",
getConnectionId($conn), getConnectionId($waiting));
$message = "You are now talking to %s.\n";
$conn->write(sprintf($message, getConnectionId($waiting)));
$waiting->write(sprintf($message, getConnectionId($conn)));
$conn->pipe($waiting)->pipe($conn);
$waiting = null;
});
$socket->listen(4000);
$loop->run();
@vslinko
Copy link

vslinko commented Oct 6, 2012

I'm thinking ++$i is better — connections must start from one.

@igorw
Copy link
Author

igorw commented Oct 9, 2012

@vslinko done. ;-)

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