Initial commit
This commit is contained in:
111
src/Socket.php
Normal file
111
src/Socket.php
Normal file
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Pdahal\Xmpp;
|
||||
|
||||
use Pdahal\Xmpp\Buffers\Response;
|
||||
use Pdahal\Xmpp\Exceptions\DeadSocket;
|
||||
|
||||
class Socket
|
||||
{
|
||||
public mixed $connection;
|
||||
protected Response $responseBuffer;
|
||||
protected Options $options;
|
||||
|
||||
/**
|
||||
* Period in microseconds for imposed timeout while doing socket_read().
|
||||
*/
|
||||
protected int $timeout = 150000;
|
||||
|
||||
/**
|
||||
* Socket constructor.
|
||||
*
|
||||
* @throws DeadSocket
|
||||
*/
|
||||
public function __construct(Options $options)
|
||||
{
|
||||
$this->responseBuffer = new Response();
|
||||
$this->connection = stream_socket_client($options->fullSocketAddress());
|
||||
|
||||
if (!$this->isAlive($this->connection)) {
|
||||
throw new DeadSocket();
|
||||
}
|
||||
|
||||
// stream_set_blocking($this->connection, true);
|
||||
stream_set_timeout($this->connection, 0, $this->timeout);
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
public function disconnect(): void
|
||||
{
|
||||
fclose($this->connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sending XML stanzas to open socket.
|
||||
*/
|
||||
public function send(string $xml)
|
||||
{
|
||||
try {
|
||||
fwrite($this->connection, $xml);
|
||||
$this->options->getLogger()->logRequest(__METHOD__.'::'.__LINE__." {$xml}");
|
||||
// $this->checkSocketStatus();
|
||||
} catch (\Exception $e) {
|
||||
$this->options->getLogger()->error(__METHOD__.'::'.__LINE__.' fwrite() failed '.$e->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->receive();
|
||||
}
|
||||
|
||||
public function receive(): void
|
||||
{
|
||||
$response = '';
|
||||
while ($out = fgets($this->connection)) {
|
||||
$response .= $out;
|
||||
}
|
||||
|
||||
if (!$response) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->responseBuffer->write($response);
|
||||
$this->options->getLogger()->logResponse(__METHOD__.'::'.__LINE__." {$response}");
|
||||
}
|
||||
|
||||
protected function isAlive($socket): bool
|
||||
{
|
||||
return $socket !== false;
|
||||
}
|
||||
|
||||
public function setTimeout($timeout): void
|
||||
{
|
||||
$this->timeout = $timeout;
|
||||
}
|
||||
|
||||
public function getResponseBuffer(): Response
|
||||
{
|
||||
return $this->responseBuffer;
|
||||
}
|
||||
|
||||
public function getOptions(): Options
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
protected function checkSocketStatus(): void
|
||||
{
|
||||
$status = socket_get_status($this->connection);
|
||||
|
||||
// echo print_r($status);
|
||||
|
||||
if ($status['eof']) {
|
||||
$this->options->getLogger()->logResponse(
|
||||
__METHOD__.'::'.__LINE__.
|
||||
" ---Probably a broken pipe, restart connection\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user