Derk-Jan Karrenbeld
11/01/2018, 2:12 AM@Test
fun keepConnectionOpen() {
// Each package ends with a 0 bytes
val bytes = randomNonZeroBytes(9000) +
ByteArray(1) +
randomNonZeroBytes(9000) +
ByteArray(1) +
randomNonZeroBytes(9000) +
ByteArray(1) +
ByteArray(1)
mock.chain(
request = mock.request().withMethod(Method.GET.value).withPath("/stream"),
response = mock.response()
.withDelay(Delay.seconds(3))
.withBody(BinaryBody(bytes, MediaType.OCTET_STREAM))
)
val keepOpenManager = FuelManager().apply {
timeoutInMillisecond = 0
timeoutReadInMillisecond = 0
}
val (_, response, result) = keepOpenManager.request(Method.GET, mock.path("stream"))
.responseObject(IgnoreDeserializer())
val (fake, _) = result
println("$fake is what was deserialized")
val openStream = response.body().toStream()
// how many bytes are available
println("${openStream.available()} approx. are available for read")
read(openStream)
}
fun read(steam: InputStream) {
steam.use {
while(true) {
// runBlocking {
println("start consuming stream")
// Implement your own handling / deserialization
val results = mutableListOf<Int>()
var byte = steam.read()
while (byte != 0) {
results.add(byte)
byte = steam.read()
}
val byteArray = results.toTypedArray()
println("Got myself ${byteArray.size} bytes")
if (results.size == 0) {
break
}
}
}
println("stream closed")
}
class IgnoreDeserializer : ResponseDeserializable<Any> {
private val fakeResult = "not actually the result"
override fun deserialize(response: Response): Any {
// don't consume stream, but keep it
// this is NOT deserialize(inputStream: InputStream) because that DOES mark the stream as consumed
return fakeResult
}
}