@ApplicationScoped
@Path("/chat")
public class ChatResource {
private static final Logger LOGGER = LoggerFactory.getLogger(ChatResource.class);
private SseBroadcaster sseBroadcaster; (1)
private Sse sse;
@Context
public synchronized void setSse(Sse sse) { (2)
if (this.sse != null) {
return;
}
this.sse = sse;
this.sseBroadcaster = sse.newBroadcaster();
this.sseBroadcaster.onClose(eventSink -> LOGGER.info("On close EventSink: {}", eventSink));
this.sseBroadcaster.onError(
(eventSink, throwable) -> LOGGER.info("On Error EventSink: {}, Throwable: {}", eventSink, throwable));
}
@GET (3)
@Produces(MediaType.SERVER_SENT_EVENTS)
public void register(@Context SseEventSink eventSink, @QueryParam("name") String name) {
LOGGER.info("Registering user: {}", name);
sseBroadcaster.register(eventSink);
eventSink.send(sse.newEvent(String.format("Welcome, %s!", name)));
broadcast(String.format("%s entered the chat room...", name));
}
@POST (4)
public void broadcast(String message) {
OutboundSseEvent event = sse.newEventBuilder().data(message).reconnectDelay(10000).build();
sseBroadcaster.broadcast(event);
}
}