Skip to content

Instantly share code, notes, and snippets.

@SOF3
Last active November 12, 2016 09:36
Show Gist options
  • Save SOF3/006ad7d839697ff9044d7eb8cf16f2f8 to your computer and use it in GitHub Desktop.
Save SOF3/006ad7d839697ff9044d7eb8cf16f2f8 to your computer and use it in GitHub Desktop.
<?php
class ReadStreamTask extends AsyncTask{
public function __construct(string $host, CommandSender $sender){ // Step 1
$this->host = $host;
parent::__construct($sender);
}
public function onRun(){
$socket = fsockopen($this->host); // Step 2
$length = Binary::readInt(fread($socket, 4)); // Step 2
if($length === 0){
$this->setResult(""); // Step 4
}
$buffer = "";
$this->publishProgress(0.0); // Step 3
for($read = 0; $read < $length; $read += 1024){
$buffer .= fread($socket, 1024); // Step 2
$this->publishProgress($read / $length); // Step 3
}
$read -= 1024;
if($read < $length) $buffer .= fread($socket, $length - $read); // Step 2
$this->setResult($buffer); // Step 4
}
public function onProgressUpdated(Server $server, $data){ // Step 3
$sender = $this->peekLocal($server); // same as fetchLocal() except that it doesn't delete the data
if(!($sender instanceof Player and !$sender->isOnline())){
$sender->sendMessage(sprintf("Downloaded %g%% data", $data * 100));
}
}
public function onCompletion(Server $server){
$sender = $this->fetchLocal($server); // remove the data finally
$result = $this->getResult(); // only call this method once, and store the result in a variable. Otherwise, PocketMine unserializes it every time.
if(!($sender instanceof Player and !$sender->isOnline())){
$sender->sendMessage(sprintf("Downloaded %g KB data, md5 hash is %s", strlen($result) / 1024, md5($result)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment