5 use Ratchet\MessageComponentInterface;
6 use Ratchet\ConnectionInterface;
9 * Meet Damien, our client connectivity application.
10 * @author andre.fourie
12 class Damien implements MessageComponentInterface
16 * General debugging switch.
19 protected $debug = false;
21 * Worker server ip address.
24 protected $workerIp = '127.0.0.1';
26 * Client websocket connections.
31 * Worker websocket connections.
39 protected $gearClient;
45 public function __construct()
47 $this->clients = array();
48 $this->workers = array();
49 $this->gearClient = new \GearmanClient();
50 $this->gearClient->addServer();
56 ### ------------------------------------------------------ CONNECTION EVENT HANDLING
58 * Handle new websocket connections.
59 * @param ConnectionInterface $from Websocket connection interface
62 public function onOpen(ConnectionInterface $conn)
64 #-> Store the new connection.
65 $this->clients[$conn->resourceId] = $conn;
68 $this->gearClient->doBackground(
72 'message' => "\nConnections: " . count($this->clients) . "\n"
73 . 'Memory usage: ' . round(memory_get_usage(true) / 1048576, 2) . 'mb'
81 * Handle received websocket messages.
82 * @param ConnectionInterface $conn Websocket connection interface
83 * @param string $message Message from connected client
86 public function onMessage(ConnectionInterface $conn, $message)
88 $workload = json_decode($message, true);
89 if (isset($workload['ping']))
91 $conn->send('{"pong":true}');
96 * Handle websocket connection closure.
97 * @param ConnectionInterface $conn Websocket connection interface
100 public function onClose(ConnectionInterface $conn)
102 #-> Client connection closed, do some cleanup.
103 unset($this->clients[$conn->resourceId]);
107 $this->gearClient->doBackground(
111 'message' => "\nConnections: " . count($this->clients) . "\n"
112 . 'Memory usage: ' . round(memory_get_usage(true) / 1048576, 2) . 'mb'
120 * Handle websocket connection error.
121 * @param ConnectionInterface $conn Websocket connection interface
122 * @param \Exception $e The exception instance
125 public function onError(ConnectionInterface $conn, \Exception $e)
127 #-> Nasty connection error, close the connection.
130 $this->gearClient->doBackground(
134 'message' => 'SocketApp Connection Error: ' . $e->getMessage()
143 * Handle new ZeroMQ message.
144 * @param String $message Serialized message from ZeroMQ
147 public function onQueueMessage($message)
150 $start = microtime(true);
151 foreach ($this->clients as $id => $conn)
153 $conn->send($message);
155 $time = round(microtime(true) - $start, 3);
156 $this->gearClient->doBackground(
160 'message' => 'Connections: ' . count($this->clients) . '; Cost: ' . $time