Created
December 19, 2012 03:41
-
-
Save jnrbsn/4334212 to your computer and use it in GitHub Desktop.
The beginnings of a really simple web server written in 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 | |
error_reporting(-1); | |
set_time_limit(0); | |
$host = '0.0.0.0'; | |
$port = 12345; | |
$max_clients = 10; | |
// Create the socket. | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
if (!is_resource($socket)) { | |
throw new Exception(socket_last_error()); | |
} | |
// Bind the socket to the port. | |
if (!socket_bind($socket, $host, $port) || !socket_listen($socket)) { | |
throw new Exception(socket_last_error($socket)); | |
} | |
echo 'Waiting for connections...',"\n"; | |
$write = null; | |
$except = null; | |
$tv_sec = null; | |
$new_client = array('socket' => null, 'address' => null, 'input' => ''); | |
$client = array_fill(0, $max_clients, $new_client); | |
while (true) { | |
$read = array($socket); | |
for ($i = 0; $i < $max_clients; ++$i) { | |
if ($client[$i]['socket'] !== null) { | |
$read[] = $client[$i]['socket']; | |
} | |
} | |
if (socket_select($read, $write, $except, $tv_sec) === 0) { | |
continue; | |
} | |
if (in_array($socket, $read)) { | |
for ($i = 0; $i < $max_clients; ++$i) { | |
if ($client[$i]['socket'] === null) { | |
$client[$i]['socket'] = socket_accept($socket); | |
if (socket_getpeername($client[$i]['socket'], $address)) { | |
$client[$i]['address'] = $address; | |
} | |
echo 'New client connected ',$i,"\n"; | |
break; | |
} else if ($i == $max_clients - 1) { | |
echo 'Too many clients...',"\n"; | |
} | |
} | |
} | |
for ($i = 0; $i < $max_clients; ++$i) { | |
if ($client[$i]['socket'] === null || !in_array($client[$i]['socket'], $read)) { | |
continue; | |
} | |
$input = socket_read($client[$i]['socket'], 1024, PHP_BINARY_READ); | |
$client[$i]['input'] .= $input; | |
if (substr($client[$i]['input'], -4) === "\r\n\r\n") { | |
$response = 'HTTP/1.1 200 OK'."\r\n". | |
'Date: '.date('r')."\r\n". | |
'Content-Type: text/html; charset=UTF-8'."\r\n\r\n". | |
'<h1>Hello, World!</h1>'."\r\n"; | |
socket_write($client[$i]['socket'], $response, strlen($response)); | |
socket_close($client[$i]['socket']); | |
echo '>>> ',$client[$i]['address'],"\n",rtrim($client[$i]['input'], "\r\n"),"\n\n"; | |
$client[$i] = $new_client; | |
} | |
} | |
} | |
// Close primary socket. | |
socket_close($socket); | |
echo 'Socket terminated',"\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment