Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Last active September 27, 2016 09:04
Show Gist options
  • Save ethaizone/bd408e9cd4d24b43c001e0492f181e48 to your computer and use it in GitHub Desktop.
Save ethaizone/bd408e9cd4d24b43c001e0492f181e48 to your computer and use it in GitHub Desktop.
Demo tcp server on PHP.
<?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