Created
January 3, 2013 17:36
-
-
Save hobodave/4445222 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Stomp | |
{ | |
public $uri = 'tcp://localhost'; | |
public $port = 61613; | |
public $connect_timeout_sec = 60; | |
public $read_timeout_sec = 60; | |
public $read_timeout_usec = 0; | |
public $socket = null; | |
public function __construct() | |
{ | |
$this->openSocket(); | |
} | |
protected function openSocket() | |
{ | |
$connect_errno = null; | |
$connect_errstr = null; | |
$this->socket = @fsockopen($this->uri, $this->port, $connect_errno, $connect_errstr, $this->connect_timeout_sec); | |
} | |
protected function hasFrameToRead() | |
{ | |
$read = array($this->socket); | |
$write = null; | |
$except = null; | |
// I'm OK with this stream_select blocking for 60 seconds. I'd rather not have it block for a short | |
// period of time and have to sleep() in an infinite loop. | |
$has_frame_to_read = @stream_select($read, $write, $except, $this->read_timeout_sec, $this->read_timeout_usec); | |
if ($has_frame_to_read !== false) { | |
$has_frame_to_read = count($read); | |
} | |
if ($has_frame_to_read === false) { | |
throw new RuntimeException('Check failed to determine if the socket is readable'); | |
} else if ($has_frame_to_read > 0) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
public function readFrame() | |
{ | |
if (!$this->hasFrameToRead()) { | |
return false; | |
} | |
$rb = 1024; | |
$data = ''; | |
$end = false; | |
do { | |
// This is the problem line. | |
// Once I know there is a frame available, I want to read it until the NULL | |
// byte \x00 is reached. | |
// However, if say the frame is 1224 bytes in length, then the first 1024 will | |
// be read instantly, and the second call to fread will block for 60 seconds | |
// since only 200 bytes are available. | |
$read = fread($this->socket, $rb); | |
if ($read === false || $read === "") { | |
$this->_reconnect(); | |
return $this->readFrame(); | |
} | |
$data .= $read; | |
if (strpos($data, "\x00") !== false) { | |
$end = true; | |
$data = trim($data, "\n"); | |
} | |
$len = strlen($data); | |
} while ($len < 2 || $end == false); | |
// Further processing of "frame" occurs here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment