1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace leocata\m1Bot\Workers; |
4
|
|
|
|
5
|
|
|
use leocata\M1\HttpClientAuthorization; |
6
|
|
|
use leocata\m1Bot\Events; |
7
|
|
|
use Ratchet\Client\Connector; |
8
|
|
|
use Ratchet\Client\WebSocket; |
9
|
|
|
use Ratchet\RFC6455\Messaging\MessageInterface; |
10
|
|
|
use React\EventLoop\Factory; |
11
|
|
|
|
12
|
|
|
class WebSocketWorker extends Events |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
private $subProtocol = 'json.api.smile-soft.com'; |
16
|
|
|
private $wssHost = 'wss://m1online.net'; |
17
|
|
|
private $host = 'm1online.net'; |
18
|
|
|
private $auth; |
19
|
|
|
private $events; |
20
|
|
|
|
21
|
|
|
public function __construct(HttpClientAuthorization $auth, Events $events) |
22
|
|
|
{ |
23
|
|
|
$this->events = $events; |
24
|
|
|
$this->auth = $auth; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function execute() |
28
|
|
|
{ |
29
|
|
|
$loop = Factory::create(); |
30
|
|
|
$connector = new Connector($loop); |
31
|
|
|
|
32
|
|
|
$connector($this->wssHost, [$this->subProtocol], ['Host' => $this->host] + $this->auth->getBasicAuth())->then( |
33
|
|
|
|
34
|
|
|
function (WebSocket $stream) { |
35
|
|
|
|
36
|
|
|
$stream->on('message', function (MessageInterface $msg) { |
37
|
|
|
$this->message($msg); |
38
|
|
|
}); |
39
|
|
|
|
40
|
|
|
$stream->on('close', function ($code = null, $reason = null) { |
41
|
|
|
$this->close($code, $reason); |
42
|
|
|
}); |
43
|
|
|
|
44
|
|
|
}, function (\Exception $e) use ($loop) { |
45
|
|
|
echo "Could not connect: {$e->getMessage()}\n"; |
46
|
|
|
$loop->stop(); |
47
|
|
|
} |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
$loop->run(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
public function getHost(): string |
57
|
|
|
{ |
58
|
|
|
return $this->host; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $host |
63
|
|
|
*/ |
64
|
|
|
public function setHost(string $host) |
65
|
|
|
{ |
66
|
|
|
$this->host = $host; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
|
|
public function getWssHost(): string |
73
|
|
|
{ |
74
|
|
|
return $this->wssHost; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param string $wssHost |
79
|
|
|
*/ |
80
|
|
|
public function setWssHost(string $wssHost) |
81
|
|
|
{ |
82
|
|
|
$this->wssHost = $wssHost; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @return string |
87
|
|
|
*/ |
88
|
|
|
public function getSubProtocol(): string |
89
|
|
|
{ |
90
|
|
|
return $this->subProtocol; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* @param string $subProtocol |
95
|
|
|
*/ |
96
|
|
|
public function setSubProtocol(string $subProtocol) |
97
|
|
|
{ |
98
|
|
|
$this->subProtocol = $subProtocol; |
99
|
|
|
} |
100
|
|
|
} |