Read not throwing exception when connection is closed (Server sent events)
See original GitHub issueI started an implementation of Server Sent Events using OkHttp as the network layer. The implementation is pretty straightforward.
The constructor takes the OkHttpClient and sets the timeout to 0 since we need to keep the connection alive.
private EventCall(OkHttpClient client, Request request) {
this.client = client.newBuilder()
.readTimeout(0, TimeUnit.SECONDS)
.writeTimeout(0, TimeUnit.SECONDS)
.connectTimeout(0, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
this.request = request.newBuilder().header("Accept", "text/event-stream").header("Cache-Control", "no-cache").build();
this.call = this.client.newCall(request);
}
Once the call is enqueued and successfully I use the StreamAllocation to created the buffer to read from. Then I block the thread with a read method that will only go out in the case of error.
private void createSSE(final EventListener listener) {
StreamAllocation streamAllocation = Internal.instance.callEngineGetStreamAllocation(call);
RealEvent source = StreamEvent.create(streamAllocation, listener);
while (source.read()) {
}
}
The read method is waiting for message from the server and parses them following the SSE specs
public boolean read() {
try {
String line = source.readUtf8LineStrict();
processLine(line);
} catch (IOException e) {
realEventListener.onError(e);
return false;
}
return true;
}
The code works, and the message is received correctly. The problem comes when I tried to handle network issues. For example, if the wifi connection is lost.
Two things happens in that case:
- The read operation throws an exception
Read error: ssl=0xae45e000: I/O error during system call, connection timed out
What is correct, since when have been disconnected - The read operation keeps blocked and no error is thrown.
In the second case, if we connect again the WiFi and we send a message from the server, the read method will get unblocked and read it, but afterward, it won’t read anything else.
The first case seems to happen more if we disconnect the wifi a bit before receiving an event, the second one is happening more often.
One solution would be to set a read timeout and try to reconnect. But this is against of what SSE defines.
I may have miss sth or I am doing something wrong. Let me know if you need further information.
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (2 by maintainers)
Top GitHub Comments
I don’t think we can merge it, but I will try to contribute back with lessons learn and improvements.
Looks like OkHttp 3.11.0 introduced experimental support for SSE after all. @skimarxall, does it make sense to merge https://github.com/heremaps/oksse with upstream then?