-
-
Save Ph3nol/3845054 to your computer and use it in GitHub Desktop.
React Chatroulette
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
{ | |
"require": { | |
"react/socket": "0.2.*" | |
} | |
} |
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 | |
// 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))); | |
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