Created
October 22, 2017 15:23
-
-
Save Gydo194/4125849e9d2f9087e03512a763ce148c to your computer and use it in GitHub Desktop.
Native PHP Pub/Sub server (BETA)
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 | |
/* | |
* PubSubServer.php | |
* native PHP Pub/Sub server | |
* Author: Gydo194 | |
* Version: 1.0 | |
* Date: 2210171714 | |
*/ | |
/* | |
Usage: | |
Initialize: | |
$server = new PubSubServer("your cache file"); | |
publish message: | |
$server->Publish("your channel","your message"); | |
listen for messages and dump to client: | |
$server->blocking_subscribe_to_http("your channel"); | |
This will listen for messages and send them to the client instantly. | |
*/ | |
class PubSubServer { | |
private $cache_file_path; | |
private $lastModifiedTime; | |
private $currentModifiedTime; | |
private $loop_delay = 15000; | |
public function __construct($file = null) { | |
if($file == null) { | |
$this->cache_file_path = __DIR__ . "PubSubServerCache.db"; | |
} else { | |
$this->cache_file_path = $file; | |
} | |
if(!file_exists($this->cache_file_path)) { | |
error_log("ERROR: PubSubServer::__construct(): cannot stat {$this->cache_file_path}."); | |
return false; | |
} | |
$this->lastModifiedTime = filemtime($this->cache_file_path); | |
$this->currentModifiedTime = $this->lastModifiedTime; | |
} | |
public function Publish($channel,$message) { | |
$data_array = array( | |
"channel" => $channel, | |
"message" => $message | |
); | |
$data = json_encode($data_array,true); | |
if(file_put_contents($this->cache_file_path, $data) == FALSE) { | |
error_log("ERROR: PubSubServer::Publish(): cannot write file."); | |
} | |
} | |
public function blocking_subscribe_to_http($channel) { | |
set_time_limit(0); | |
while(true) { | |
ob_flush(); | |
flush(); | |
clearstatcache(); | |
$this->currentModifiedTime = filemtime($this->cache_file_path); | |
if($this->currentModifiedTime > $this->lastModifiedTime) { | |
$this->lastModifiedTime = $this->currentModifiedTime; | |
$raw = file_get_contents($this->cache_file_path); | |
if($raw) { | |
$data = json_decode($raw,true); | |
if(array_key_exists("channel", $data) && array_key_exists("message", $data)) { | |
//var_dump($data); | |
if($data["channel"] === $channel) { | |
print($data["message"]); | |
} | |
} | |
} else { | |
error_log("ERROR: PubSubServer::blocking_subscribe_to_http(): Cannot read file."); | |
} | |
} | |
usleep($this->loop_delay); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment