Search code examples
javaokhttpserver-sent-events

Understanding socket timeout when using okhttp-sse


I'm using okhttp-sse to consume server side events in Java.

OkHttpClient httpClient = new OkHttpClient();
String sseUrl = getSseUrl();
Request request = new Request.Builder()
    .url(sseUrl)
    .build();
EventSource.Factory factory = EventSources.createFactory(httpClient);
factory.newEventSource(request, listener);

This works and I receive events, but it fails after 10 seconds due to a SocketTimeoutException. I discovered that okhttp has a default timeout of 10 seconds, so this makes sense.

I increased the timeouts on my client to 1 minute, but now I get that SocketTimeoutException after 3 minutes. I don't understand what is going on. I would have expected the timeout after 1 minute.

OkHttpClient httpClient = new OkHttpClient.Builder()
    .connectTimeout(1, TimeUnit.MINUTES)
    .readTimeout(1, TimeUnit.MINUTES)
    .writeTimeout(1, TimeUnit.MINUTES)
    .build();

Can anyone shed some light on this?


Solution

  • The solution for okhttp-sse is to set the timeouts to 0 to indicate no timeout.

    OkHttpClient sseHttpClient = new OkHttpClient.Builder()
        .connectTimeout(0, TimeUnit.MINUTES) // no timeout
        .readTimeout(0, TimeUnit.MINUTES) // no timeout
        .writeTimeout(0, TimeUnit.MINUTES) // no timeout
        .build();