Java Magazine, September/October 2016
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2016 42 enterprise java The SseEventSource is created by calling the target method on a WebTarget registering an SseEventSource Listener and opening the connection After successfully opening the connection the current thread continues and the listener which in this case would be dataConsumer accept is called as soon as events arrive SseEventSource handles all required plumbing including reconnecting after a connection loss by sending an appropriate Last Event ID header and then handling Retry After headers sent from the server appropriately If a more sophisticated way is needed for instance to manually control the Last Event ID header you can manually request an SseEventInput from the server public class StatefulSseClient private final WebTarget target ClientBuilder newClient target private final Consumer String dataConsumer private String lastEventId private SseEventInput eventInput public StatefulSseClient Consumer String dataConsumer this dataConsumer dataConsumer public void start eventInput target request MediaType SERVER_ SENT_ EVENTS header HttpHeaders LAST_ EVENT_ ID_ HEADER lastEventId get SseEventInput class new Thread while eventInput isClosed final InboundSseEvent event eventInput read if event null lastEventId event getId dataConsumer accept event readData start public void stop if eventInput null eventInput isClosed try eventInput close catch IOException e suppress By requesting the input directly all required information has to be sent manually and potential reconnects need to be handled manually Therefore the client sends the text event stream HTTP header and expects the response to be an SseEventInput type that is handled appropriately by the JAX RS implementation This event input is used to receive the actual incoming events Because the eventInput read method blocks until some Consumers can call start and stop to resume and pause the stream and all events that happen during the pause are replayed after resuming
You must have JavaScript enabled to view digital editions.