|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace MallardDuck\Whois; |
|
4
|
|
|
|
|
5
|
|
|
use MallardDuck\Whois\Exceptions\SocketClientException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* A simple socket stream client. |
|
9
|
|
|
* |
|
10
|
|
|
* @author mallardduck <[email protected]> |
|
11
|
|
|
* |
|
12
|
|
|
* @copyright lucidinternets.com 2020 |
|
13
|
|
|
* |
|
14
|
|
|
* @version ?.?.? |
|
15
|
|
|
*/ |
|
16
|
|
|
final class SocketClient |
|
17
|
|
|
{ |
|
18
|
|
|
protected $socketUri = null; |
|
19
|
|
|
protected $socket = null; |
|
20
|
|
|
protected $timeout = 30; |
|
21
|
|
|
protected $connected = false; |
|
22
|
|
|
|
|
23
|
40 |
|
public function __construct(string $socketUri, int $timeout = 30) |
|
24
|
|
|
{ |
|
25
|
40 |
|
$this->socketUri = $socketUri; |
|
26
|
40 |
|
$this->timeout = $timeout; |
|
27
|
40 |
|
} |
|
28
|
|
|
|
|
29
|
34 |
|
public function connect(): self |
|
30
|
|
|
{ |
|
31
|
34 |
|
$fp = stream_socket_client($this->socketUri, $errno, $errstr, $this->timeout); |
|
32
|
34 |
|
if (!is_resource($fp) && false === $fp) { |
|
33
|
|
|
$message = sprintf("Stream Connection Failed: %s", $errstr); |
|
34
|
|
|
throw new SocketClientException($message, $errno); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
34 |
|
$this->socket = $fp; |
|
38
|
34 |
|
$this->connected = true; |
|
39
|
34 |
|
return $this; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
2 |
|
public function isConnected(): bool |
|
43
|
|
|
{ |
|
44
|
2 |
|
return $this->connected; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
34 |
|
public function writeString(string $string) |
|
48
|
|
|
{ |
|
49
|
34 |
|
if (!$this->connected) { |
|
50
|
2 |
|
$message = sprintf("The calling method %s requires the socket to be connected", __FUNCTION__); |
|
51
|
2 |
|
throw new SocketClientException($message); |
|
52
|
|
|
} |
|
53
|
32 |
|
return stream_socket_sendto($this->socket, $string); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
32 |
|
public function readAll(): string |
|
57
|
|
|
{ |
|
58
|
32 |
|
if (!$this->connected) { |
|
59
|
2 |
|
$message = sprintf("The calling method %s requires the socket to be connected", __FUNCTION__); |
|
60
|
2 |
|
throw new SocketClientException($message); |
|
61
|
|
|
} |
|
62
|
30 |
|
return stream_get_contents($this->socket); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
40 |
|
public function disconnect(): self |
|
66
|
|
|
{ |
|
67
|
40 |
|
if (!is_null($this->socket)) { |
|
68
|
34 |
|
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); |
|
69
|
34 |
|
fclose($this->socket); |
|
70
|
|
|
} |
|
71
|
40 |
|
$this->socket = null; |
|
72
|
40 |
|
$this->connected = false; |
|
73
|
|
|
|
|
74
|
40 |
|
return $this; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
20 |
|
public function __destruct() |
|
78
|
|
|
{ |
|
79
|
20 |
|
$this->disconnect(); |
|
80
|
20 |
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|