Handler.php 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. /**
  3. * Hoa
  4. *
  5. *
  6. * @license
  7. *
  8. * New BSD License
  9. *
  10. * Copyright © 2007-2017, Hoa community. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions are met:
  14. * * Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * * Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * * Neither the name of the Hoa nor the names of its contributors may be
  20. * used to endorse or promote products derived from this software without
  21. * specific prior written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  24. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  25. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  26. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
  27. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  28. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  29. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  30. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  31. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  32. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. namespace Hoa\Socket\Connection;
  36. use Hoa\Exception as HoaException;
  37. use Hoa\Socket;
  38. /**
  39. * Class \Hoa\Socket\Connection\Handler.
  40. *
  41. * This class provides a connection handler: a complete connection skeleton. We
  42. * are able to run() a connection (client or server), to merge() with other ones
  43. * and to send messages in different ways (A -> A, A -> B, A -> *\A etc.).
  44. *
  45. * @copyright Copyright © 2007-2017 Hoa community
  46. * @license New BSD License
  47. */
  48. abstract class Handler
  49. {
  50. /**
  51. * Original connection.
  52. *
  53. * @var \Hoa\Socket\Connection
  54. */
  55. protected $_originalConnection = null;
  56. /**
  57. * Current connection.
  58. *
  59. * @var \Hoa\Socket\Connection
  60. */
  61. protected $_connection = null;
  62. /**
  63. * All other connections that have been merged.
  64. *
  65. * @var array
  66. */
  67. protected $_connections = [];
  68. /**
  69. * Constructor. Must be called.
  70. *
  71. * @param \Hoa\Socket\Connection $connection Connection.
  72. */
  73. public function __construct(Connection $connection)
  74. {
  75. $this->_originalConnection = $connection;
  76. $this->setConnection($connection);
  77. return;
  78. }
  79. /**
  80. * Set current connection.
  81. *
  82. * @param \Hoa\Socket\Connection $connection Connection.
  83. * @return \Hoa\Socket\Connection
  84. */
  85. protected function setConnection(Connection $connection)
  86. {
  87. $old = $this->_connection;
  88. $this->_connection = $connection;
  89. return $old;
  90. }
  91. /**
  92. * Get original connection.
  93. *
  94. * @return \Hoa\Socket\Connection
  95. */
  96. protected function getOriginalConnection()
  97. {
  98. return $this->_originalConnection;
  99. }
  100. /**
  101. * Get current connection.
  102. *
  103. * @return \Hoa\Socket\Connection
  104. */
  105. public function getConnection()
  106. {
  107. return $this->_connection;
  108. }
  109. /**
  110. * Get all merged connections.
  111. *
  112. * @return array
  113. */
  114. public function getMergedConnections()
  115. {
  116. return $this->_connections;
  117. }
  118. /**
  119. * The node dedicated part of the run() method.
  120. * A run is pretty simple, schematically:
  121. *
  122. * while (true) foreach ($connection->select() as $node)
  123. * // body
  124. *
  125. * The body is given by this method.
  126. *
  127. * @param \Hoa\Socket\Node $node Node.
  128. * @return void
  129. */
  130. abstract protected function _run(Socket\Node $node);
  131. /**
  132. * Run the connection.
  133. *
  134. * @return void
  135. */
  136. public function run()
  137. {
  138. $connection = $this->getConnection();
  139. if ($connection instanceof Socket\Server) {
  140. $connection->connectAndWait();
  141. } else {
  142. $connection->connect();
  143. }
  144. do {
  145. foreach ($connection->select() as $node) {
  146. // Connection has failed to detect the node, maybe it is a resource
  147. // from a merged client in a server.
  148. if (false === is_object($node)) {
  149. $socket = $node;
  150. foreach ($this->getMergedConnections() as $other) {
  151. $otherConnection = $other->getOriginalConnection();
  152. if (!($otherConnection instanceof Socket\Client)) {
  153. continue;
  154. }
  155. $node = $otherConnection->getCurrentNode();
  156. if ($node->getSocket() === $socket) {
  157. $other->_run($node);
  158. continue 2;
  159. }
  160. }
  161. }
  162. foreach ($this->getMergedConnections() as $other) {
  163. if (true === $connection->is($other->getOriginalConnection())) {
  164. $other->_run($node);
  165. continue 2;
  166. }
  167. }
  168. $this->_run($node);
  169. }
  170. } while (SUCCEED);
  171. $connection->disconnect();
  172. return;
  173. }
  174. /**
  175. * Merge a connection into this one.
  176. * If we have two connections that must run at the same time, the
  177. * Hoa\Socket\Connection::consider() and Hoa\Socket\Connection::is() methods
  178. * are helpful but this whole class eases the merge of “high-level”
  179. * connections.
  180. *
  181. * @param \Hoa\Socket\Connection\Handler $other Connection to merge.
  182. * @return \Hoa\Socket\Connection\Handler
  183. */
  184. public function merge(self $other)
  185. {
  186. $thisConnection = $this->getConnection();
  187. $otherConnection = $other->getConnection();
  188. $thisConnection->consider($otherConnection);
  189. if ($otherConnection instanceof Socket\Server) {
  190. $other->setConnection($thisConnection);
  191. }
  192. $this->_connections[] = $other;
  193. return $this;
  194. }
  195. /**
  196. * The sending dedicated part of the self::send() method.
  197. * If the send() method is overrided with more arguments, this method could
  198. * return a function: it works like a currying.
  199. *
  200. * @param string $message Message.
  201. * @param \Hoa\Socket\Node $node Node (if null, current node).
  202. * @return void
  203. */
  204. abstract protected function _send($message, Socket\Node $node);
  205. /**
  206. * Send a message to a specific node.
  207. *
  208. * @param string $message Message.
  209. * @param \Hoa\Socket\Node $node Node (if null, current node).
  210. * current node).
  211. * @return mixed
  212. */
  213. public function send($message, Socket\Node $node = null)
  214. {
  215. if (null === $node) {
  216. $node = $this->getConnection()->getCurrentNode();
  217. }
  218. if (null === $node) {
  219. return null;
  220. }
  221. $old = $this->getConnection()->_setStream($node->getSocket());
  222. try {
  223. $send = $this->_send($message, $node);
  224. } catch (\Exception $e) {
  225. $this->getConnection()->_setStream($old);
  226. throw $e;
  227. }
  228. if ($send instanceof \Closure) {
  229. $self = $this;
  230. return function () use (&$send, &$old, &$self) {
  231. try {
  232. $out = call_user_func_array($send, func_get_args());
  233. } finally {
  234. $self->getConnection()->_setStream($old);
  235. }
  236. return $out;
  237. };
  238. }
  239. $this->getConnection()->_setStream($old);
  240. return $send;
  241. }
  242. /**
  243. * Broadcast a message, i.e. send the message to all other nodes except the
  244. * current one.
  245. *
  246. * @param string $message Message.
  247. * @param … … …
  248. * @return void
  249. */
  250. public function broadcast($message)
  251. {
  252. $currentNode = $this->getConnection()->getCurrentNode();
  253. $arguments = func_get_args();
  254. array_unshift(
  255. $arguments,
  256. function (Socket\Node $node) use ($currentNode) {
  257. return $node !== $currentNode;
  258. }
  259. );
  260. return call_user_func_array([$this, 'broadcastIf'], $arguments);
  261. }
  262. /**
  263. * Broadcast a message to a subset of nodes that fulfill a predicate.
  264. *
  265. * @param \Closure $predicate Predicate. Take a node in argument.
  266. * @param string $message Message.
  267. * @param … … …
  268. * @return void
  269. * @throws \Hoa\Exception\Group
  270. */
  271. public function broadcastIf(\Closure $predicate, $message)
  272. {
  273. $connection = $this->getConnection();
  274. $currentSocket = $this->getOriginalConnection()->getSocket();
  275. $arguments = array_slice(func_get_args(), 2);
  276. array_unshift($arguments, $message, null);
  277. $callable = [$this, 'send'];
  278. $exceptions = new HoaException\Group(
  279. 'Message cannot be sent to some nodes.'
  280. );
  281. foreach ($connection->getNodes() as $node) {
  282. if (true === $predicate($node) &&
  283. $node->getConnection()->getSocket() === $currentSocket) {
  284. $arguments[1] = $node;
  285. try {
  286. call_user_func_array($callable, $arguments);
  287. } catch (Socket\Exception $e) {
  288. $exceptions[$node->getId()] = $e;
  289. }
  290. }
  291. }
  292. if (0 < $exceptions->count()) {
  293. throw $exceptions;
  294. }
  295. return;
  296. }
  297. }