1 // Copyright (c) 2006- Facebook
2 // Distributed under the Thrift Software License
4 // See accompanying file LICENSE or visit the Thrift site at:
5 // http://developers.facebook.com/thrift/
7 package com
.facebook
.thrift
.transport
;
9 import java
.io
.ByteArrayInputStream
;
10 import java
.io
.ByteArrayOutputStream
;
12 import com
.facebook
.thrift
.TByteArrayOutputStream
;
15 * Socket implementation of the TTransport interface. To be commented soon!
17 * @author Mark Slee <mcslee@facebook.com>
19 public class TFramedTransport
extends TTransport
{
22 * Underlying transport
24 private TTransport transport_
= null;
29 private final TByteArrayOutputStream writeBuffer_
=
30 new TByteArrayOutputStream(1024);
35 private ByteArrayInputStream readBuffer_
= null;
38 * Whether to frame input
40 private boolean frameRead_
= true;
43 * Whether to frame output
45 private boolean frameWrite_
= true;
48 * Constructor wraps around another tranpsort
50 public TFramedTransport(TTransport transport
) {
51 this(transport
, true, true);
55 * Constructor wraps around another tranpsort
57 public TFramedTransport(TTransport transport
, boolean in
, boolean out
) {
58 transport_
= transport
;
63 public void setFrameRead(boolean frameRead
) {
64 frameRead_
= frameRead
;
67 public void setFrameWrite(boolean frameWrite
) {
68 frameWrite_
= frameWrite
;
71 public void open() throws TTransportException
{
75 public boolean isOpen() {
76 return transport_
.isOpen();
83 public int read(byte[] buf
, int off
, int len
) throws TTransportException
{
85 return transport_
.read(buf
, off
, len
);
88 if (readBuffer_
!= null) {
89 int got
= readBuffer_
.read(buf
, off
, len
);
95 // Read another frame of data
98 return readBuffer_
.read(buf
, off
, len
);
101 private void readFrame() throws TTransportException
{
102 byte[] i32rd
= new byte[4];
103 transport_
.readAll(i32rd
, 0, 4);
105 ((i32rd
[0] & 0xff) << 24) |
106 ((i32rd
[1] & 0xff) << 16) |
107 ((i32rd
[2] & 0xff) << 8) |
110 byte[] buff
= new byte[size
];
111 transport_
.readAll(buff
, 0, size
);
112 readBuffer_
= new ByteArrayInputStream(buff
);
115 public void write(byte[] buf
, int off
, int len
) throws TTransportException
{
117 transport_
.write(buf
, off
, len
);
120 writeBuffer_
.write(buf
, off
, len
);
123 public void flush() throws TTransportException
{
129 byte[] buf
= writeBuffer_
.get();
130 int len
= writeBuffer_
.len();
131 writeBuffer_
.reset();
133 byte[] i32out
= new byte[4];
134 i32out
[0] = (byte)(0xff & (len
>> 24));
135 i32out
[1] = (byte)(0xff & (len
>> 16));
136 i32out
[2] = (byte)(0xff & (len
>> 8));
137 i32out
[3] = (byte)(0xff & (len
));
138 transport_
.write(i32out
, 0, 4);
139 transport_
.write(buf
, 0, len
);