Carter
04/24/2023, 5:33 PMcall.respondTextWriter(status = HttpStatusCode.Created) {
answerFlow.collect { answer ->
write(jsonParser.encodeToString(answer))
write("\n")
flush()
}
}
And the client is doing this
httpClient.prepareRequest {
method = <http://HttpMethod.Post|HttpMethod.Post>
contentType(ContentType.Application.Json)
setBody(questionBuilder)
}.execute { response ->
if (!response.status.isSuccess()) {
// handle error
} else {
val channel: ByteReadChannel = response.body()
while (!channel.isClosedForRead) {
val line = channel.readUTF8Line()
if (line?.isNotBlank() == true) {
println("Receiving: $line")
val responseObj = jsonParser.decodeFromString<Obj>(line)
emit(responseObj)
}
}
}
}
I’m pretty confident the client-side code is correct, because I tested it against a different web service known to return similarly streamed responses.
As best I can tell, it seems like the server is buffering the response, ignoring the flush calls, and returning all the data once the Writer is closed. Is there something I’m missing here?
I also tried respondOutputStream
with similar results.Aleksei Tirman [JB]
04/24/2023, 5:38 PMApplicationCall.respondBytesWriter
method that isn’t blocking?
call.respondBytesWriter(status = HttpStatusCode.Created) {
answerFlow.collect { answer ->
writeStringUtf8(jsonParser.encodeToString(answer))
writeStringUtf8("\n")
flush()
}
}
Carter
04/24/2023, 5:43 PMCarter
04/24/2023, 5:44 PMcall.respondBytesWriter {
repeat(10) {
println("writing")
writeStringUtf8("\n")
flush()
delay(500)
}
And I can see the logs show writing completes before the client receives anythingAleksei Tirman [JB]
04/25/2023, 7:12 AMembeddedServer(Netty, port = 3333) {
routing {
get("/stream") {
call.respondBytesWriter {
repeat(10) {
writeStringUtf8("Hello you\n")
flush()
delay(1000)
}
}
}
}
}.start(wait = true)
Both curl and Ktor’s HTTP client with the CIO engine receive a line as soon as it is sent.Carter
04/25/2023, 9:57 AMCarter
04/25/2023, 2:38 PMZoltan Demant
04/25/2023, 5:47 PMCarter
04/25/2023, 6:23 PMCarter
04/26/2023, 11:18 AMAleksei Tirman [JB]
04/28/2023, 7:06 AMCarter
04/29/2023, 5:09 PMCarter
06/01/2023, 2:17 PMAleksei Tirman [JB]
06/02/2023, 7:29 AMinstall(CORS) {
anyHost()
}
Carter
06/02/2023, 10:05 AMCarter
06/05/2023, 7:29 PMAleksei Tirman [JB]
06/06/2023, 9:03 AMCarter
06/06/2023, 10:50 AMCarter
06/06/2023, 10:51 AMCarter
06/06/2023, 3:36 PM