4 * Copyright 2005-2006 The Apache Software Foundation
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 /* vim: set expandtab tabstop=3 shiftwidth=3: */
21 require_once 'Stomp/Frame.php';
28 * @author Hiram Chirino <hiram@hiramchirino.com>
29 * @author Dejan Bosanac <dejan@nighttale.net>
30 * @author Michael Caplan <mcaplan@labnet.net>
31 * @version $Revision: 43 $
36 * Perform request synchronously
43 * Default prefetch size
47 public $prefetchSize = 1;
50 * Client id used for durable subscriptions
54 public $clientId = null;
56 protected $_brokerUri = null;
57 protected $_socket = null;
58 protected $_hosts = array();
59 protected $_params = array();
60 protected $_subscriptions = array();
61 protected $_defaultPort = 61613;
62 protected $_currentHost = - 1;
63 protected $_attempts = 10;
64 protected $_username = '';
65 protected $_password = '';
66 protected $_sessionId;
67 protected $_read_timeout_seconds = 60;
68 protected $_read_timeout_milliseconds = 0;
73 * @param string $brokerUri Broker URL
74 * @throws Stomp_Exception
76 public function __construct ($brokerUri)
78 $this->_brokerUri = $brokerUri;
82 * Initialize connection
84 * @throws Stomp_Exception
86 protected function _init ()
88 $pattern = "|^(([a-zA-Z]+)://)+\(*([a-zA-Z0-9\.:/i,-]+)\)*\??([a-zA-Z0-9=]*)$|i";
89 if (preg_match($pattern, $this->_brokerUri, $regs)) {
93 if ($scheme != "failover") {
94 $this->_processUrl($this->_brokerUri);
96 $urls = explode(",", $hosts);
97 foreach ($urls as $url) {
98 $this->_processUrl($url);
101 if ($params != null) {
102 parse_str($params, $this->_params);
105 require_once 'Stomp/Exception.php';
106 throw new Stomp_Exception("Bad Broker URL {$this->_brokerUri}");
112 * @param string $url Broker URL
113 * @throws Stomp_Exception
116 protected function _processUrl ($url)
118 $parsed = parse_url($url);
120 array_push($this->_hosts, array($parsed['host'] , $parsed['port'] , $parsed['scheme']));
122 require_once 'Stomp/Exception.php';
123 throw new Stomp_Exception("Bad Broker URL $url");
127 * Make socket connection to the server
129 * @throws Stomp_Exception
131 protected function _makeConnection ()
133 if (count($this->_hosts) == 0) {
134 require_once 'Stomp/Exception.php';
135 throw new Stomp_Exception("No broker defined");
138 // force disconnect, if previous established connection exists
141 $i = $this->_currentHost;
144 while (! $connected && $att ++ < $this->_attempts) {
145 if (isset($this->_params['randomize']) && $this->_params['randomize'] == 'true') {
146 $i = rand(0, count($this->_hosts) - 1);
148 $i = ($i + 1) % count($this->_hosts);
150 $broker = $this->_hosts[$i];
153 $scheme = $broker[2];
155 $port = $this->_defaultPort;
157 if ($this->_socket != null) {
158 fclose($this->_socket);
159 $this->_socket = null;
161 $this->_socket = @fsockopen($scheme . '://' . $host, $port);
162 if (!is_resource($this->_socket) && $att >= $this->_attempts && !array_key_exists($i + 1, $this->_hosts)) {
163 require_once 'Stomp/Exception.php';
164 throw new Stomp_Exception("Could not connect to $host:$port ($att/{$this->_attempts})");
165 } else if (is_resource($this->_socket)) {
167 $this->_currentHost = $i;
172 require_once 'Stomp/Exception.php';
173 throw new Stomp_Exception("Could not connect to a broker");
179 * @param string $username
180 * @param string $password
182 * @throws Stomp_Exception
184 public function connect ($username = '', $password = '')
186 $this->_makeConnection();
187 if ($username != '') {
188 $this->_username = $username;
190 if ($password != '') {
191 $this->_password = $password;
193 $headers = array('login' => $this->_username , 'passcode' => $this->_password);
194 if ($this->clientId != null) {
195 $headers["client-id"] = $this->clientId;
197 $frame = new Stomp_Frame("CONNECT", $headers);
198 $this->_writeFrame($frame);
199 $frame = $this->readFrame();
200 if ($frame instanceof Stomp_Frame && $frame->command == 'CONNECTED') {
201 $this->_sessionId = $frame->headers["session"];
204 require_once 'Stomp/Exception.php';
205 if ($frame instanceof Stomp_Frame) {
206 throw new Stomp_Exception("Unexpected command: {$frame->command}", 0, $frame->body);
208 throw new Stomp_Exception("Connection not acknowledged");
214 * Check if client session has ben established
218 public function isConnected ()
220 return !empty($this->_sessionId) && is_resource($this->_socket);
223 * Current stomp session ID
227 public function getSessionId()
229 return $this->_sessionId;
232 * Send a message to a destination in the messaging system
234 * @param string $destination Destination queue
235 * @param string|Stomp_Frame $msg Message
236 * @param array $properties
237 * @param boolean $sync Perform request synchronously
240 public function send ($destination, $msg, $properties = null, $sync = null)
242 if ($msg instanceof Stomp_Frame) {
243 $msg->headers['destination'] = $destination;
244 $msg->headers = array_merge($msg->headers, $properties);
247 $headers = $properties;
248 $headers['destination'] = $destination;
249 $frame = new Stomp_Frame('SEND', $headers, $msg);
251 $this->_prepareReceipt($frame, $sync);
252 $this->_writeFrame($frame);
253 return $this->_waitForReceipt($frame, $sync);
256 * Prepair frame receipt
258 * @param Stomp_Frame $frame
259 * @param boolean $sync
261 protected function _prepareReceipt (Stomp_Frame $frame, $sync)
263 $receive = $this->sync;
264 if ($sync !== null) {
267 if ($receive == true) {
268 $frame->headers['receipt'] = md5(microtime());
274 * @param Stomp_Frame $frame
275 * @param boolean $sync
277 * @throws Stomp_Exception
279 protected function _waitForReceipt (Stomp_Frame $frame, $sync)
282 $receive = $this->sync;
283 if ($sync !== null) {
286 if ($receive == true) {
287 $id = (isset($frame->headers['receipt'])) ? $frame->headers['receipt'] : null;
291 $frame = $this->readFrame();
292 if ($frame instanceof Stomp_Frame && $frame->command == 'RECEIPT') {
293 if ($frame->headers['receipt-id'] == $id) {
296 require_once 'Stomp/Exception.php';
297 throw new Stomp_Exception("Unexpected receipt id {$frame->headers['receipt-id']}", 0, $frame->body);
300 require_once 'Stomp/Exception.php';
301 if ($frame instanceof Stomp_Frame) {
302 throw new Stomp_Exception("Unexpected command {$frame->command}", 0, $frame->body);
304 throw new Stomp_Exception("Receipt not received");
311 * Register to listen to a given destination
313 * @param string $destination Destination queue
314 * @param array $properties
315 * @param boolean $sync Perform request synchronously
317 * @throws Stomp_Exception
319 public function subscribe ($destination, $properties = null, $sync = null)
321 $headers = array('ack' => 'client');
322 $headers['activemq.prefetchSize'] = $this->prefetchSize;
323 if ($this->clientId != null) {
324 $headers["activemq.subcriptionName"] = $this->clientId;
326 if (isset($properties)) {
327 foreach ($properties as $name => $value) {
328 $headers[$name] = $value;
331 $headers['destination'] = $destination;
332 $frame = new Stomp_Frame('SUBSCRIBE', $headers);
333 $this->_prepareReceipt($frame, $sync);
334 $this->_writeFrame($frame);
335 if ($this->_waitForReceipt($frame, $sync) == true) {
336 $this->_subscriptions[$destination] = $properties;
343 * Remove an existing subscription
345 * @param string $destination
346 * @param array $properties
347 * @param boolean $sync Perform request synchronously
349 * @throws Stomp_Exception
351 public function unsubscribe ($destination, $properties = null, $sync = null)
354 if (isset($properties)) {
355 foreach ($properties as $name => $value) {
356 $headers[$name] = $value;
359 $headers['destination'] = $destination;
360 $frame = new Stomp_Frame('UNSUBSCRIBE', $headers);
361 $this->_prepareReceipt($frame, $sync);
362 $this->_writeFrame($frame);
363 if ($this->_waitForReceipt($frame, $sync) == true) {
364 unset($this->_subscriptions[$destination]);
371 * Start a transaction
373 * @param string $transactionId
374 * @param boolean $sync Perform request synchronously
376 * @throws Stomp_Exception
378 public function begin ($transactionId = null, $sync = null)
381 if (isset($transactionId)) {
382 $headers['transaction'] = $transactionId;
384 $frame = new Stomp_Frame('BEGIN', $headers);
385 $this->_prepareReceipt($frame, $sync);
386 $this->_writeFrame($frame);
387 return $this->_waitForReceipt($frame, $sync);
390 * Commit a transaction in progress
392 * @param string $transactionId
393 * @param boolean $sync Perform request synchronously
395 * @throws Stomp_Exception
397 public function commit ($transactionId = null, $sync = null)
400 if (isset($transactionId)) {
401 $headers['transaction'] = $transactionId;
403 $frame = new Stomp_Frame('COMMIT', $headers);
404 $this->_prepareReceipt($frame, $sync);
405 $this->_writeFrame($frame);
406 return $this->_waitForReceipt($frame, $sync);
409 * Roll back a transaction in progress
411 * @param string $transactionId
412 * @param boolean $sync Perform request synchronously
414 public function abort ($transactionId = null, $sync = null)
417 if (isset($transactionId)) {
418 $headers['transaction'] = $transactionId;
420 $frame = new Stomp_Frame('ABORT', $headers);
421 $this->_prepareReceipt($frame, $sync);
422 $this->_writeFrame($frame);
423 return $this->_waitForReceipt($frame, $sync);
426 * Acknowledge consumption of a message from a subscription
427 * Note: This operation is always asynchronous
429 * @param string|Stomp_Frame $messageMessage ID
430 * @param string $transactionId
432 * @throws Stomp_Exception
434 public function ack ($message, $transactionId = null)
436 if ($message instanceof Stomp_Frame) {
437 $frame = new Stomp_Frame('ACK', $message->headers);
438 $this->_writeFrame($frame);
442 if (isset($transactionId)) {
443 $headers['transaction'] = $transactionId;
445 $headers['message-id'] = $message;
446 $frame = new Stomp_Frame('ACK', $headers);
447 $this->_writeFrame($frame);
452 * Graceful disconnect from the server
455 public function disconnect ()
459 if ($this->clientId != null) {
460 $headers["client-id"] = $this->clientId;
463 if (is_resource($this->_socket)) {
464 $this->_writeFrame(new Stomp_Frame('DISCONNECT', $headers));
465 fclose($this->_socket);
467 $this->_socket = null;
468 $this->_sessionId = null;
469 $this->_currentHost = -1;
470 $this->_subscriptions = array();
471 $this->_username = '';
472 $this->_password = '';
475 * Write frame to server
477 * @param Stomp_Frame $stompFrame
479 protected function _writeFrame (Stomp_Frame $stompFrame)
481 if (!is_resource($this->_socket)) {
482 require_once 'Stomp/Exception.php';
483 throw new Stomp_Exception('Socket connection hasn\'t been established');
486 $data = $stompFrame->__toString();
487 $r = fwrite($this->_socket, $data, strlen($data));
488 if ($r === false || $r == 0) {
490 $this->_writeFrame($stompFrame);
495 * Set timeout to wait for content to read
497 * @param int $seconds_to_wait Seconds to wait for a frame
498 * @param int $milliseconds Milliseconds to wait for a frame
500 public function setReadTimeout($seconds, $milliseconds = 0)
502 $this->_read_timeout_seconds = $seconds;
503 $this->_read_timeout_milliseconds = $milliseconds;
507 * Read responce frame from server
509 * @return Stomp_Frame|Stomp_Message_Map|boolean False when no frame to read
511 public function readFrame ()
513 if (!$this->hasFrameToRead()) {
520 $read = fgets($this->_socket, $rb);
521 if ($read === false) {
523 return $this->readFrame();
526 $len = strlen($data);
527 } while (($len < 2 || ! ($data[$len - 2] == "\x00" && $data[$len - 1] == "\n")));
529 list ($header, $body) = explode("\n\n", $data, 2);
530 $header = explode("\n", $header);
533 foreach ($header as $v) {
534 if (isset($command)) {
535 list ($name, $value) = explode(':', $v, 2);
536 $headers[$name] = $value;
541 $frame = new Stomp_Frame($command, $headers, trim($body));
542 if (isset($frame->headers['amq-msg-type']) && $frame->headers['amq-msg-type'] == 'MapMessage') {
543 require_once 'Stomp/Message/Map.php';
544 return new Stomp_Message_Map($frame);
551 * Check if there is a frame to read
555 public function hasFrameToRead()
557 $read = array($this->_socket);
561 $has_frame_to_read = stream_select($read, $write, $except, $this->_read_timeout_seconds, $this->_read_timeout_milliseconds);
563 if ($has_frame_to_read === false) {
564 throw new Stomp_Exception('Check failed to determin if the socket is readable');
565 } else if ($has_frame_to_read > 0) {
573 * Reconnects and renews subscriptions (if there were any)
574 * Call this method when you detect connection problems
576 protected function _reconnect ()
578 $subscriptions = $this->_subscriptions;
580 $this->connect($this->_username, $this->_password);
581 foreach ($subscriptions as $dest => $properties) {
582 $this->subscribe($dest, $properties);
586 * Graceful object desruction
589 public function __destruct()