1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace MySQLReplication\Socket; |
5
|
|
|
|
6
|
|
|
class Socket implements SocketInterface |
7
|
|
|
{ |
8
|
|
|
private $socket; |
9
|
|
|
|
10
|
58 |
|
public function __destruct() |
11
|
|
|
{ |
12
|
58 |
|
if ($this->isConnected()) { |
13
|
58 |
|
socket_shutdown($this->socket); |
14
|
58 |
|
socket_close($this->socket); |
15
|
|
|
} |
16
|
58 |
|
} |
17
|
|
|
|
18
|
58 |
|
public function isConnected(): bool |
19
|
|
|
{ |
20
|
58 |
|
return is_resource($this->socket); |
21
|
|
|
} |
22
|
|
|
|
23
|
58 |
|
public function connectToStream(string $host, int $port): void |
24
|
|
|
{ |
25
|
58 |
|
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); |
26
|
58 |
|
if (!$this->socket) { |
27
|
|
|
throw new SocketException( |
28
|
|
|
SocketException::SOCKET_UNABLE_TO_CREATE_MESSAGE . $this->getSocketErrorMessage(), |
29
|
|
|
SocketException::SOCKET_UNABLE_TO_CREATE_CODE |
30
|
|
|
); |
31
|
|
|
} |
32
|
58 |
|
socket_set_block($this->socket); |
33
|
58 |
|
socket_set_option($this->socket, SOL_SOCKET, SO_KEEPALIVE, 1); |
34
|
|
|
|
35
|
58 |
|
if (!socket_connect($this->socket, $host, $port)) { |
36
|
|
|
throw new SocketException($this->getSocketErrorMessage(), $this->getSocketErrorCode()); |
37
|
|
|
} |
38
|
58 |
|
} |
39
|
|
|
|
40
|
|
|
private function getSocketErrorMessage(): string |
41
|
|
|
{ |
42
|
|
|
return socket_strerror($this->getSocketErrorCode()); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function getSocketErrorCode(): int |
46
|
|
|
{ |
47
|
|
|
return socket_last_error(); |
48
|
|
|
} |
49
|
|
|
|
50
|
58 |
|
public function readFromSocket(int $length): string |
51
|
|
|
{ |
52
|
58 |
|
$received = socket_recv($this->socket, $buf, $length, MSG_WAITALL); |
53
|
58 |
|
if ($length === $received) { |
54
|
58 |
|
return $buf; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
// http://php.net/manual/en/function.socket-recv.php#47182 |
58
|
|
|
if (0 === $received) { |
59
|
|
|
throw new SocketException( |
60
|
|
|
SocketException::SOCKET_DISCONNECTED_MESSAGE, |
61
|
|
|
SocketException::SOCKET_DISCONNECTED_CODE |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
throw new SocketException($this->getSocketErrorMessage(), $this->getSocketErrorCode()); |
66
|
|
|
} |
67
|
|
|
|
68
|
58 |
|
public function writeToSocket(string $data): void |
69
|
|
|
{ |
70
|
58 |
|
if (!socket_write($this->socket, $data, strlen($data))) { |
71
|
|
|
throw new SocketException( |
72
|
|
|
SocketException::SOCKET_UNABLE_TO_WRITE_MESSAGE . $this->getSocketErrorMessage(), |
73
|
|
|
SocketException::SOCKET_UNABLE_TO_WRITE_CODE |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |