4 * Copyright (c) 2006- Facebook
5 * Distributed under the Thrift Software License
7 * See accompanying file LICENSE or visit the Thrift site at:
8 * http://developers.facebook.com/thrift/
10 * @package thrift.transport
11 * @author Mark Slee <mcslee@facebook.com>
15 * Framed transport. Writes and reads data in chunks that are stamped with
18 * @package thrift.transport
19 * @author Mark Slee <mcslee@facebook.com>
21 class TFramedTransport
extends TTransport
{
24 * Underlying transport object.
31 * Buffer for read data.
38 * Buffer for queued output data
45 * Whether to frame reads
52 * Whether to frame writes
61 * @param TTransport $transport Underlying transport
63 public function __construct($transport=null, $read=true, $write=true) {
64 $this->transport_
= $transport;
66 $this->write_
= $write;
69 public function isOpen() {
70 return $this->transport_
->isOpen();
73 public function open() {
74 $this->transport_
->open();
77 public function close() {
78 $this->transport_
->close();
82 * Reads from the buffer. When more data is required reads another entire
83 * chunk and serves future reads out of that.
85 * @param int $len How much data
87 public function read($len) {
89 return $this->transport_
->read($len);
92 if (strlen($this->rBuf_
) === 0) {
96 // Just return full buff
97 if ($len >= strlen($this->rBuf_
)) {
104 $out = substr($this->rBuf_
, 0, $len);
105 $this->rBuf_
= substr($this->rBuf_
, $len);
110 * Put previously read data back into the buffer
112 * @param string $data data to return
114 public function putBack($data) {
115 if (strlen($this->rBuf_
) === 0) {
116 $this->rBuf_
= $data;
118 $this->rBuf_
= ($data . $this->rBuf_
);
123 * Reads a chunk of data into the internal read buffer.
125 private function readFrame() {
126 $buf = $this->transport_
->readAll(4);
127 $val = unpack('N', $buf);
130 $this->rBuf_
= $this->transport_
->readAll($sz);
134 * Writes some data to the pending output buffer.
136 * @param string $buf The data
137 * @param int $len Limit of bytes to write
139 public function write($buf, $len=null) {
140 if (!$this->write_
) {
141 return $this->transport_
->write($buf, $len);
144 if ($len !== null && $len < strlen($buf)) {
145 $buf = substr($buf, 0, $len);
147 $this->wBuf_
.= $buf;
151 * Writes the output buffer to the stream in the format of a 4-byte length
152 * followed by the actual data.
154 public function flush() {
155 if (!$this->write_
) {
156 return $this->transport_
->flush();
159 $out = pack('N', strlen($this->wBuf_
));
160 $out .= $this->wBuf_
;
161 $this->transport_
->write($out);
162 $this->transport_
->flush();