Last active
September 27, 2016 09:04
-
-
Save ethaizone/bd408e9cd4d24b43c001e0492f181e48 to your computer and use it in GitHub Desktop.
Demo tcp server on PHP.
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 | |
// Composer install this package. | |
// https://github.com/reactphp/socket | |
// Command support: broadcast, who | |
require 'vendor/autoload.php'; | |
$loop = React\EventLoop\Factory::create(); | |
$socket = new React\Socket\Server($loop); | |
$connections = []; | |
$socket->on('connection', function ($conn) use (&$connections) { | |
$conn->name = stream_socket_get_name($conn->stream, true); | |
$connections[] = $conn; | |
$conn->write("Hello there!\n"); | |
$conn->write("Your connection is ".$conn->name."\n"); | |
$conn->on('data', function ($data) use ($conn, &$connections) { | |
$data = trim($data); | |
if (strpos($data, "broadcast") === 0) { | |
foreach($connections as $c) { | |
if ($conn->name != $c->name) { | |
$c->write($conn->name . " want to send broadcast to you.\n"); | |
} | |
} | |
return; | |
} | |
if ($data == "who") { | |
$conn->write("Clients: \n"); | |
foreach($connections as $c) { | |
$conn->write("-> ".$c->name); | |
if ($conn->name == $c->name) { | |
$conn->write(" (This is you.)"); | |
} | |
$conn->write("\n"); | |
} | |
$conn->write("Broadcasted!\n"); | |
return; | |
} | |
$conn->write("Received!\n"); | |
}); | |
$conn->on('close', function ($data) use ($conn, &$connections) { | |
foreach($connections as $k => $c) { | |
if ($conn->name == $c->name) { | |
unset($connections[$k]); | |
} | |
} | |
}); | |
}); | |
$socket->listen(1337); | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment