Server Side Event not firing in Jersey 2.8 using SSE

大兔子大兔子 提交于 2019-12-01 22:17:34

问题


I am trying with a sample example given in the official documentation of Jersey SSE

Refer " 14.5.2. Asynchronous SSE processing with EventSource " in the below link https://jersey.github.io/documentation/2.8/user-guide.html#example-simple-sse

My Code is as below

Client code -

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

}

Then in one of the action method, I am just initialising the event listening as follows

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

Client's Web.xml has init-param as follow

<init-param>
    <param-name>javax.ws.rs.Application</param-name>
    <param-value>com.framework.MyApplication</param-value>
</init-param>

Server Code -

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

Expected output at client side is as follows

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!

But nothing is printing at client side. Am I missing something over here ? I have a doubt, the client.Target , it should have "http://:8080/server/events" ? OR it should be just "http://:8080/events"


回答1:


SSE worked fine for me finally. there are couple of things we need to do

  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 ...");
     }
    


来源:https://stackoverflow.com/questions/23672354/server-side-event-not-firing-in-jersey-2-8-using-sse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!