Created
October 6, 2012 13:41
-
-
Save igorw/3844965 to your computer and use it in GitHub Desktop.
React Chatroulette
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
{ | |
"require": { | |
"react/socket": "0.2.*" | |
} | |
} |
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 | |
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm thinking
++$i
is better — connections must start from one.