Skip to content

Instantly share code, notes, and snippets.

@Codezigineer
Last active March 25, 2023 21:05
Show Gist options
  • Save Codezigineer/6fd8ebbd86a05b5419dd4062c0193a2a to your computer and use it in GitHub Desktop.
Save Codezigineer/6fd8ebbd86a05b5419dd4062c0193a2a to your computer and use it in GitHub Desktop.
Simpler HTTP Socket server in PHP (Apache, no modules)
<?php
declare(strict_types=1);
$input = fopen("php://input");
class HTTPSocketServer {
public ?callable $onData = null;
private bool $serverStarted = false;
public function __construct(callable $onNewClient, callable $onLeaveClient, ?callable $onData = null)
{
if($_SERVER['REQUEST_METHOD'] !== 'GET')
{
http_response_code(405);
exit();
};
if(
$onNewClient();
register_shutdown_function($onLeaveClient);
$this->$onData = $onData;
};
public function _onData()
{
if(!$this->$serverStarted)
{
this->$serverStarted = true;
new EvTimer(0.005, 1, $this->_onData);
};
if(isset($this->$onData)) $this->$onData(fread($input));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment