gpt4 book ai didi

java - Jersey SSE 客户端不工作

转载 作者:搜寻专家 更新时间:2023-11-01 03:48:50 26 4
gpt4 key购买 nike

我是 Jersey SSE Client API 的新手,我有一个连续发送事件的 servlet。当我从浏览器调用 URL 时,我看到它在工作。当尝试使用 Jersey SSE 客户端调用相同内容时,它没有按预期工作,我没有看到任何异常被抛出。

这是我为此使用的代码。

服务器:

    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;
}
}

}

Jersey 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();
}
}

Jersey Client onEvent 从未触发。将不胜感激任何帮助。让我知道,如果我遗漏了什么。

谢谢,普拉迪普

最佳答案

SseFeature 不适用于这种分块输出,我们必须使用 ChunkedInput 来读取事件。

关于java - Jersey SSE 客户端不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com