Jersey 2.8中使用SSE时,服务器端事件未触发

3
我将尝试使用Jersey SSE官方文档中提供的示例进行操作。
请参阅下面链接中的“14.5.2.使用EventSource进行异步SSE处理”: https://jersey.github.io/documentation/2.8/user-guide.html#example-simple-sse 以下是我的代码:
客户端代码 -
  public class ClientSSEEventManager {
        public void WaitForEvents() {
            // Client client = ClientBuilder.newBuilder()
            // .register(SseFeature.class).build();
            // WebTarget target =
            // client.target("http://localhost:8080/server/events");
            //
            // EventInput eventInput = target.request().get(EventInput.class);
            // while (!eventInput.isClosed()) {
            // final InboundEvent inboundEvent = eventInput.read();
            // if (inboundEvent == null) {
            // // connection has been closed
            // break;
            // }
            // System.out.println(inboundEvent.getName() + "; "
            // + inboundEvent.readData(String.class));
            // }

            Client client = ClientBuilder.newBuilder().register(SseFeature.class)
                    .build();
            WebTarget target = client.target("http://localhost:8080/server/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, "message-to-client");
            eventSource.open();
        }
    }

public class MyApplication extends ResourceConfig {
    public MyApplication(){
     super(ClientSSEEventManager.class, SseFeature.class);
    }
//   Set<Class<?>> classes = new HashSet<Class<?>>() {
//          /**
//       * 
//       */
//      private static final long serialVersionUID = 1L;
//
//          { add(ClientSSEEventManager.class);
//          }};
//
//      @Override
//      public Set<Class<?>> getClasses() {
//          return classes;
//      }

}

然后在其中一个操作方法中,我只是按照以下方式初始化事件监听

//Start listening to event from server
     ClientSSEEventManager clientSSEEventManager = new                      ClientSSEEventManager();
clientSSEEventManager.WaitForEvents();
///

客户端的Web.xml文件有以下init-param参数:
<init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.framework.MyApplication</param-value>
</init-param>

服务器代码 -

@Path("events")
public class ServerSSEServerEventManager {
    @GET
    @Produces(SseFeature.SERVER_SENT_EVENTS)
    public EventOutput getNotificationEvents(){
         final EventOutput eventOutput = new EventOutput();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int i = 0; i < 10; i++) {
                            // ... code that waits 1 second
                            final OutboundEvent.Builder eventBuilder
                            = new OutboundEvent.Builder();
                            eventBuilder.name("message-to-client");
                            eventBuilder.data(String.class,
                                "Hello world " + i + "!");
                            final OutboundEvent event = eventBuilder.build();
                            eventOutput.write(event);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(
                            "Error when writing the event.", e);
                    } finally {
                        try {
                            eventOutput.close();
                        } catch (IOException ioClose) {
                            throw new RuntimeException(
                                "Error when closing the event output.", ioClose);
                        }
                    }
                }
            }).start();
            return eventOutput;
    }
}

客户端期望的输出如下所示。
message-to-client; Hello world 0!
message-to-client; Hello world 1!
message-to-client; Hello world 2!
message-to-client; Hello world 3!
message-to-client; Hello world 4!
message-to-client; Hello world 5!
message-to-client; Hello world 6!
message-to-client; Hello world 7!
message-to-client; Hello world 8!
message-to-client; Hello world 9!

但客户端没有打印任何内容。 我有一个疑问,客户端目标应该是 "http://:8080/server/events" 还是只是 "http://:8080/events"?


您的服务器URL取决于应用程序的“上下文路径”。如果您部署为“server”,则路径应为http://localhost:8080/server/events。我建议在服务器端添加一些日志记录,并将Jackson日志过滤器添加到客户端client.register(new LoggingFilter(LOG, true));,以便查看客户端发送/接收的内容。 - Baldy
如果我直接在浏览器中打开URL,例如http://serverip:8080/server/events,则会调用服务器端的getNotificationEvents方法。但是,如果我通过运行上面代码中显示的客户端应用程序来执行相同的操作,则不会调用服务器端的getNotificationEvents方法。 - Sadanand
好的,看了你的客户端代码,你设置了事件处理程序,但是你从未发出GET请求。 - Baldy
@Baldy 当我们打开连接时,不就是发出GET请求吗?你能否给我更新一下代码片段,告诉我需要做哪些更改? - Sadanand
在上面的示例中,服务器立即响应客户端,但实际上应该在服务器端发生更改时推送事件。那么服务器如何推送事件?我需要在哪里添加什么代码? - Sadanand
嗨@Sadanand,你有找到这个问题的答案吗?我遇到了与此处详细描述的类似问题http://stackoverflow.com/questions/30917568/jersey-sse-client-not-receiving-anything-from-server-thread - a.hrdie
1个回答

1

SSE 对我最终起作用了。 我们需要做几件事情。

  1. SSE listener in Springs

      @Singleton
         @Path("/events")
         public class NotificationHandler {
             @Path("/register/{userName}")
         @Produces(SseFeature.SERVER_SENT_EVENTS)
         @GET
         public @ResponseBody EventOutput registerForAnEventSummary(
                @PathParam("userName") String userName) {
            }
         }
    
  2. Call a service that make a call to notify all clients

     PostMethod postMethod = null;
            postMethod = new PostMethod(
                    resourceBundle.getString("localhost:8080")
                            + resourceBundle.getString("applicationnotifier")
                            + resourceBundle
                                    .getString("sse/events/broadcast/"));
    
  3. A broadcaster

     @Path("/broadcast")
        @POST
         @Produces(MediaType.TEXT_PLAIN)
         @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
        public String broadcastNotifications(@FormParam("message") String message) { }
    
  4. Javascript - listen to all SSE events by registering

     var notificationBaseURL =  ""; //The URL Where your services are hosted
     function listenAllEvents() {
         if ( (EventSource) !== "undefined") {
    
        var source = new EventSource(
        notificationBaseURL+"applicationnotifier/sse/events/register/"+loggedInUserName);
        source.onmessage = notifyEvent;
    } else {
        console.log("Sorry no event data sent - ");
        }
     }
    
     function notifyEvent(event) {
        var responseJson = JSON.parse(event.data);
        alert("... Notification Received ...");
     }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接