Skip to content

Commit

Permalink
Gracefully handles client connection close before count is reached.
Browse files Browse the repository at this point in the history
Signed-off-by: Santiago Pericas-Geertsen <[email protected]>
  • Loading branch information
spericas committed Oct 25, 2024
1 parent da99502 commit 99cfbd6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package io.helidon.examples.webserver.sse;

import java.io.UncheckedIOException;
import java.lang.System.Logger.Level;
import java.time.Duration;

import io.helidon.http.sse.SseEvent;
Expand All @@ -31,6 +33,7 @@
*/
class SseService implements HttpService {

private static final System.Logger LOGGER = System.getLogger(SseService.class.getName());
private static final JsonProvider JSON_PROVIDER = JsonProvider.provider();

@Override
Expand All @@ -44,11 +47,16 @@ void sseText(ServerRequest req, ServerResponse res) throws InterruptedException
int delay = req.query().first("delay").asInt().orElse(0);
try (SseSink sseSink = res.sink(SseSink.TYPE)) {
for (int i = 0; i < count; i++) {
sseSink.emit(SseEvent.builder()
.comment("comment#" + i)
.name("my-event")
.data("data#" + i)
.build());
try {
sseSink.emit(SseEvent.builder()
.comment("comment#" + i)
.name("my-event")
.data("data#" + i)
.build());
} catch (UncheckedIOException e) {
LOGGER.log(Level.DEBUG, e.getMessage()); // connection close?
return;
}

if (delay > 0) {
Thread.sleep(Duration.ofSeconds(delay));
Expand All @@ -62,9 +70,14 @@ void sseJson(ServerRequest req, ServerResponse res) throws InterruptedException
int delay = req.query().first("delay").asInt().orElse(0);
try (SseSink sseSink = res.sink(SseSink.TYPE)) {
for (int i = 0; i < count; i++) {
sseSink.emit(SseEvent.create(JSON_PROVIDER.createObjectBuilder()
.add("data", "data#" + i)
.build()));
try {
sseSink.emit(SseEvent.create(JSON_PROVIDER.createObjectBuilder()
.add("data", "data#" + i)
.build()));
} catch (UncheckedIOException e) {
LOGGER.log(Level.DEBUG, e.getMessage()); // connection close?
return;
}

if (delay > 0) {
Thread.sleep(Duration.ofSeconds(delay));
Expand Down
3 changes: 1 addition & 2 deletions examples/webserver/sse/src/main/resources/logging.properties
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
# limitations under the License.
#

handlers=java.util.logging.ConsoleHandler
handlers=io.helidon.logging.jul.HelidonConsoleHandler
java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS.%1$tL %5$s%6$s%n
# Global logging level. Can be overridden by specific loggers
.level=INFO
io.helidon.webserver.level=INFO

0 comments on commit 99cfbd6

Please sign in to comment.