Skip to content

Instantly share code, notes, and snippets.

@ikariiin
Created March 3, 2016 12:04
Show Gist options
  • Save ikariiin/b18dfe54892c85451234 to your computer and use it in GitHub Desktop.
Save ikariiin/b18dfe54892c85451234 to your computer and use it in GitHub Desktop.
<?php
/**
* User: gourab
* Date: 3/3/16
* Time: 1:30 PM
* Testing Threads To Create a Simple Server
*/
error_reporting(E_ALL);
class Server extends Thread {
private $port;
private $listen_ip;
private $socket;
private $type;
/**
* Server constructor.
* @param string $listen_ip
* @param int $port
* @param string $type
*/
public function __construct(string $listen_ip, int $port, string $type = "development")
{
$this->listen_ip = $listen_ip;
$this->port = $port;
$this->type = $type;
return $this->initiateSocket();
}
/**
* Initializes the socket
* @return bool
*/
public function initiateSocket() {
// Initialize a socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if($sock === false) {
echo "Failed to initialize socket";
if($this->type == "development") {
echo ": " . socket_strerror(socket_last_error()) . "\n";
} else {
echo ": REASON CLASSIFIED\n";
}
return false;
}
// Socket Created. Continue.
// Bind the socket with the specified address and port
if(socket_bind($sock, $this->listen_ip, $this->port) === false) {
echo "Failed to bind socket";
if($this->type == "development") {
echo ": " . socket_strerror(socket_last_error()) . "\n";
} else {
echo ": REASON CLASSIFIED\n";
}
return false;
}
// Binding Complete.
// Make the socket listen
if(socket_listen($sock) === false) {
echo "Failed to make socket listen";
if($this->type == "development") {
echo ": " . socket_strerror(socket_last_error()) . "\n";
} else {
echo ": REASON CLASSIFIED\n";
}
return false;
}
// Complete. Initialized. Bind-ed. Listening.
// Make the $sock a part of this class.
$this->socket = $sock;
// Work Complete.
return true;
}
public function handle_start() {
while(($client = socket_accept($this->socket))) {
$this->start();
}
}
public function run()
{
$client = $this->socket;
if($client) {
$header = 0;
while(($chars = socket_read($client, 1024, PHP_NORMAL_READ))) {
$head[$header] = trim($chars);
if($header > 0) {
if(!$head[$header] && !$head[$header - 1]) {
echo "Malformed Request.";
break;
}
}
$header++;
}
/** @noinspection PhpUndefinedVariableInspection */
foreach($head as $header) {
if($header) {
$headers[] = $header;
}
}
/** @noinspection PhpUndefinedVariableInspection */
var_dump($headers);
}
}
public function throwException($error, $errCode) {
// Experimental
// Not Implemented
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment