forked from clue/reactphp-ssdp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
71 lines (57 loc) · 1.94 KB
/
Copy pathClient.php
File metadata and controls
71 lines (57 loc) · 1.94 KB
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
<?php
namespace Clue\React\Ssdp;
use React\EventLoop\LoopInterface;
use Clue\React\Multicast\Factory as MulticastFactory;
use React\Promise\Deferred;
class Client
{
const ADDRESS = '239.255.255.250:1900';
private $loop;
private $multicast;
public function __construct(LoopInterface $loop, MulticastFactory $multicast = null)
{
if ($multicast === null) {
$multicast = new MulticastFactory($loop);
}
$this->loop = $loop;
$this->multicast = $multicast;
}
public function search($searchTarget = 'ssdp:all', $mx = 2)
{
$data = "M-SEARCH * HTTP/1.1\r\n";
$data .= "HOST: " . self::ADDRESS . "\r\n";
$data .= "MAN: \"ssdp:discover\"\r\n";
$data .= "MX: $mx\r\n";
$data .= "ST: $searchTarget\r\n";
$data .= "\r\n";
$socket = $this->multicast->createSender();
// TODO: The TTL for the IP packet SHOULD default to 2 and SHOULD be configurable.
$timer = $this->loop->addTimer($mx, function() use ($socket, &$deferred) {
$deferred->resolve();
$socket->close();
});
$deferred = new Deferred(function () use ($socket, &$timer) {
// canceling resulting promise cancels timer and closes socket
$timer->cancel();
$socket->close();
throw new RuntimeException('Cancelled');
});
$that = $this;
$socket->on('message', function ($data, $remote) use ($deferred, $that) {
$message = $that->parseMessage($data, $remote);
$deferred->progress($message);
});
$socket->send($data, self::ADDRESS);
return $deferred->promise();
}
/** @internal */
public function parseMessage($message, $remote)
{
// TODO: parse message into message model
$message = array(
'data' => $message,
'_sender' => $remote
);
return $message;
}
}