我正试图从这个tutorial在java中实现SSE客户端。 当使用post方法实现为Servlet客户端时,它工作正常。但是当我在Java项目中使用main方法和servlet中使用相同的jar文件实现相同时,它不起作用。这是我和目标URI一起使用的代码: -
import javax.ws.rs.Consumes;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
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;
public class SSEreceive {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Client client = ClientBuilder.newBuilder().register(SseFeature.class).build();
WebTarget target = ((Client)client).target("http://www.w3schools.com/html/demo_sse.php");
EventSource eventSource = (EventSource)EventSource.target(target).build();
EventListener listener = new EventListener() {
@Override
//@Consumes(MediaType.APPLICATION_JSON)
public void onEvent(InboundEvent inboundEvent) {
// System.out.println(inboundEvent.getName() + "; " + inboundEvent.readData(String.class));
System.out.println(inboundEvent.readData(String.class));
}
};
//eventSource.register(listener, "message-to-client");
eventSource.register(listener);
eventSource.open();
System.out.println("Connection tried");
eventSource.close();
} catch (ProcessingException pe) {
pe.printStackTrace();
System.out.println(pe.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
有些人可以帮助我,为什么这在Java项目中不起作用?