对于Jersey SSE Client API来说,我有一个不断发送事件的servlet。当我从浏览器调用URL时,我看到它正常工作。当尝试使用Jersey SSE客户端调用它时,它没有按预期工作,我没有看到任何异常被抛出。
以下是我正在使用的代码。
SERVLET:
package com.abc.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestStream extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
res.setContentType("text/event-stream");
res.setCharacterEncoding("UTF-8");
PrintWriter printWriter = null;
while(true)
{
try {
printWriter = res.getWriter();
printWriter.print("data: Thread Will wait for 10 seconds and push the notifications \n\n");
printWriter.print("data: " + Calendar.getInstance().getTime() +"\n\n");
res.flushBuffer();
Thread.sleep(10000);
}
catch(IOException ie) {
printWriter.close();
break;
}
catch(InterruptedException ie){
printWriter.close();
break;
}
}
}
}
泽西岛SSE客户代码:
package com.abc.test;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.sse.EventSource;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
public class ListenerThread implements Runnable {
private int i = 0;
private Thread t;
public void start() {
if (t == null) {
t = new Thread(this);
t.start();
}
}
@Override
public void run() {
EventSource eventSource = null;
try {
// TODO Auto-generated method stub
Client client = ClientBuilder.newBuilder()
.register(SseFeature.class).build();
WebTarget target = client.target("http://172.20.14.19:8080/TestStream/SSE");
eventSource = new EventSource(target) {
@Override
public void onEvent(InboundEvent inboundEvent) {
System.out.println(inboundEvent.getName() + "; "
+ inboundEvent.readData(String.class));
}
};
while (i <= 10) {
try {
Thread.sleep(6000);
System.out.println("Printing I value : " + i);
System.out.println("Is Event Source OPEN : " + eventSource.isOpen());
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Throwable t) {
System.out.println("Inside Throwable");
t.printStackTrace();
} finally {
if (null != eventSource)
eventSource.close();
}
}
}
泽西岛客户端onEvent从未触发过。将不胜感激任何帮助。如果我遗漏了什么,请告诉我。
谢谢, 普拉迪普
答案 0 :(得分:0)
SseFeature不适用于这种chuncked输出,我们必须使用ChunkedInput来读取事件。
答案 1 :(得分:0)
由于您使用的是EventSource和EventListener,我认为您需要注册事件并打开
eventSource.register(listener, "EVENT NAME"
);
eventSource.open();