1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| <?php
declare(strict_types=1);
namespace Test\test;
class Connector
{
private $address;
private $port;
private $socket = FALSE;
private $connected = FALSE;
public function __construct($address, int $port = 5250) {
$this->address = $address;
$this->port = $port;
}
public function connectSocket() {
if ($this->connected) {
return TRUE;
}
$this->socket = @pfsockopen($this->address, $this->port, $errno, $errstr, 10);
if ($this->socket !== FALSE) {
$this->connected = TRUE;
}
return $this->connected;
}
public function makeRequest($out) {
if (!$this->connectSocket()) { // reconnect if not connected
return FALSE;
}
$test = fwrite($this->socket, $out . "\r\n");
$line = fgets($this->socket);
$line = explode(" ", $line);
$status = intval($line[0], 10);
$hasResponse = true;
if ($status === 200) { // several lines followed by empty line
$endSequence = "\r\n\r\n";
}
else if ($status === 201) { // one line of data returned
$endSequence = "\r\n";
}
else {
$hasResponse = FALSE;
}
if ($hasResponse) {
$response = stream_get_line($this->socket, 10000, $endSequence);
}
else {
$response = FALSE;
}
return array("status"=>$status, "response"=>$response);
}
public static function escapeString($string) {
return str_replace('"', '\"', str_replace("\n", '\n', str_replace('\\', '\\\\', $string)));
}
public function closeSocket() {
if (!$this->connected) {
return TRUE;
}
fclose($this->socket);
$this->connected = FALSE;
return TRUE;
}
public function __destruct() {
$this->closeSocket();
}
} |
Partager