I have written a rudimentary Java application to consume SSE (server-sent events) streamed from a Node.js server, using the Jersey SSE client. However, I am unable to receive the events. To verify the server component is working as expected, I used the curl
as follows:
curl -v -H "Accept: text/event-stream" http://localhost:8080/events/
I get the following response:
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET /events/ HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: text/event-stream
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/event-stream
< Cache-Control: no-cache
< Connection: keep-alive
< Date: Wed, 26 Apr 2017 17:12:00 GMT
< Transfer-Encoding: chunked
<
event: ping
data: 0.6637400726922664
event: ping
data: 0.8538157046725585
The code for my SSE client in Java is as follows (Java 8, Jersey Client 1.19.3, Jersey Media SSE 2.25.1):
import org.glassfish.jersey.media.sse.EventListener;
import org.glassfish.jersey.media.sse.EventSource;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
public class NodeCaptureSSE {
public static void main(String[] args) {
Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = client.target("http://localhost:8080/events/");
EventSource eventSource = EventSource.target(target).build();
EventListener listener = new EventListener() {
@Override
public void onEvent(InboundEvent inboundEvent) {
System.out.println(inboundEvent.getName() + "; " + inboundEvent.readData(String.class));
}
};
eventSource.register(listener, "ping");
eventSource.open();
System.out.println("Connected to SSE source...");
try {
Thread.sleep(25_000);
}
catch (InterruptedException ie) {
System.err.println("Exception: " + ie.getMessage());
}
eventSource.close();
System.out.println("Closed connection to SSE source");
}
}
The only output I see on the screen is:
Connected to SSE source...
followed by an exit, after 25 seconds. Since the server is streaming named events ("ping"), I specified that while registering the listener to the event source. Omitting the second parameter to the eventSource.register(...);
did not do anything, although I did not expect it to. I also removed the ending /
in the URL, but that yields a 404 Not Found
(as expected). I hope to get any pointers in the right direction.