Last active
February 19, 2022 13:51
-
-
Save maryo/bf80428e3f1894c5e807782b55b92885 to your computer and use it in GitHub Desktop.
Naive (HTTP) socket server baseline
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 | |
$host = '0.0.0.0'; | |
$port = 8080; | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); | |
socket_bind($socket, $host, $port); | |
socket_listen($socket); | |
socket_set_nonblock($socket); | |
echo "Listening on {$host}:{$port}\n\n"; | |
$sockets = [$socket]; | |
while (true) { | |
$readableSockets = $sockets; | |
$null = null; | |
if (!socket_select($readableSockets, $null, $null, 0, 10)) { | |
continue; | |
} | |
$index = array_search($socket, $readableSockets, true); | |
if ($index !== false) { | |
if ($client = socket_accept($socket)) { | |
$sockets[] = $client; | |
} | |
unset($readableSockets[$index]); | |
} | |
foreach ($readableSockets as $readableSocket) { | |
$request = ''; | |
while ($length = @socket_recv($readableSocket, $data, 1024, 0)) { | |
$request .= $data; | |
} | |
$index = array_search($readableSocket, $sockets, true); | |
unset($sockets[$index]); | |
$error = socket_last_error($readableSocket); | |
if ($error === SOCKET_ECONNRESET) { | |
socket_clear_error($readableSocket); | |
continue; | |
} | |
echo "Received: \n{$request}"; | |
$headers = [ | |
'HTTP/1.1 200 OK ', | |
'Content-Type: text/html', | |
'', | |
'', | |
]; | |
$body = 'TEST'; | |
$response = implode("\r\n", $headers) . $body; | |
@socket_write($client, $response, strlen($response)); | |
@socket_close($client); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment