clients = array(); $this->workers = array(); $this->gearClient = new \GearmanClient(); $this->gearClient->addServer(); } ### ------------------------------------------------------ CONNECTION EVENT HANDLING /** * Handle new websocket connections. * @param ConnectionInterface $from Websocket connection interface * @return null */ public function onOpen(ConnectionInterface $conn) { #-> Store the new connection. $this->clients[$conn->resourceId] = $conn; if ($this->debug) { $this->gearClient->doBackground( 'Log', json_encode( array( 'message' => "\nConnections: " . count($this->clients) . "\n" . 'Memory usage: ' . round(memory_get_usage(true) / 1048576, 2) . 'mb' ) ) ); } } /** * Handle received websocket messages. * @param ConnectionInterface $conn Websocket connection interface * @param string $message Message from connected client * @return null */ public function onMessage(ConnectionInterface $conn, $message) { $workload = json_decode($message, true); if (isset($workload['ping'])) { $conn->send('{"pong":true}'); } } /** * Handle websocket connection closure. * @param ConnectionInterface $conn Websocket connection interface * @return null */ public function onClose(ConnectionInterface $conn) { #-> Client connection closed, do some cleanup. unset($this->clients[$conn->resourceId]); gc_collect_cycles(); if ($this->debug) { $this->gearClient->doBackground( 'Log', json_encode( array( 'message' => "\nConnections: " . count($this->clients) . "\n" . 'Memory usage: ' . round(memory_get_usage(true) / 1048576, 2) . 'mb' ) ) ); } } /** * Handle websocket connection error. * @param ConnectionInterface $conn Websocket connection interface * @param \Exception $e The exception instance * @return null */ public function onError(ConnectionInterface $conn, \Exception $e) { #-> Nasty connection error, close the connection. if ($this->debug) { $this->gearClient->doBackground( 'Log', json_encode( array( 'message' => 'SocketApp Connection Error: ' . $e->getMessage() ) ) ); } $conn->close(); } /** * Handle new ZeroMQ message. * @param String $message Serialized message from ZeroMQ * @return null */ public function onQueueMessage($message) { #-> Broadcast. $start = microtime(true); foreach ($this->clients as $id => $conn) { $conn->send($message); } $time = round(microtime(true) - $start, 3); $this->gearClient->doBackground( 'Log', json_encode( array( 'message' => 'Connections: ' . count($this->clients) . '; Cost: ' . $time ) ) ); } }