我已經編寫了一個基本的Java應用程序,使用Jersey SSE客戶端來使用從Node.js服務器流式傳輸的SSE(服務器發送的事件)。但是,我無法收到這些事件。要驗證的服務器組件工作正常,我用curl
如下:Jersey SSE客戶端沒有收到事件
curl -v -H "Accept: text/event-stream" http://localhost:8080/events/
我得到如下回應:
* 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
在Java我SSE客戶端的代碼如下(Java的8,澤西島客戶端1.19.3,澤西媒介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");
}
}
我在屏幕上看到的唯一輸出是:
Connected to SSE source...
後面是25秒後的退出。由於服務器正在流式傳輸命名事件(「ping」),我指定在將偵聽器註冊到事件源時。省略第二個參數到eventSource.register(...);
沒有做任何事情,但我沒有想到。我還刪除了網址中的結尾/
,但這會產生404 Not Found
(如預期的那樣)。我希望能夠朝正確的方向發展。
有沒有辦法讓連接長時間打開?,澤西島客戶端會像瀏覽器一樣工作嗎? –