Last active
August 13, 2023 11:25
-
-
Save timacdonald/06d93448bc77fe955d1f9fecdb8de3ae to your computer and use it in GitHub Desktop.
This file contains 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 | |
$log = fn ($message) => print '['.number_format(microtime(true), 4, '.', '').'] '.$message.PHP_EOL; | |
$bail = function ($reason = null) use ($log) { | |
$reason ??= socket_strerror(socket_last_error()); | |
$log($reason); | |
exit(1); | |
}; | |
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
$socket || $bail(); | |
pcntl_async_signals(true); | |
pcntl_signal(SIGINT, fn () => exit(1), false); | |
register_shutdown_function(function () use ($socket, $log) { | |
socket_close($socket); | |
$log('Socket closed'); | |
}); | |
@socket_bind($socket, 'localhost', 1234) || $bail(); | |
@socket_listen($socket, backlog: 1) || $bail(); | |
socket_set_nonblock($socket) || $bail('Unable to set socket to non-blocking'); | |
$log('Ready for incoming connections'); | |
while (true) { | |
$log('Waiting for an incoming connection'); | |
$read = [$socket]; | |
$write = []; | |
$except = []; | |
$changes = @socket_select($read, $write, $except, 10); | |
$changes === false && $bail(); | |
if ($changes === 0) { | |
continue; | |
} | |
$connection = @socket_accept($socket); | |
$connection || $bail(); | |
$log('Connection received'); | |
socket_set_nonblock($connection) || $bail('Unable to set socket to non-blocking'); | |
$log('Connection set to non-blocking'); | |
$message = ''; | |
do { | |
$log('Reading from the socket'); | |
$message .= $read = socket_read($connection, 10_000, PHP_BINARY_READ); | |
} while ($read !== false); | |
$log("Received\n=======\n{$message}======="); | |
$written = socket_write($connection, <<< 'HTTP_RESPONSE' | |
HTTP/1.0 200 OK | |
Hello world | |
HTTP_RESPONSE); | |
$written === false && $bail(); | |
$log('Response sent'); | |
socket_shutdown($connection); | |
socket_close($connection); | |
$connection = null; | |
$log('Socket closed'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment