@GET
  @Produces(SseFeature.SERVER_SENT_EVENTS)
  public EventOutput getServerSentEvents() {
    final EventOutput eventOutput = new EventOutput();
    TASK_EXECUTOR.execute(
        () -> {
          try {
            for (int i = 0; i < 10; i++) {
              LOG.info("sleeping 100ms");
              try {
                Thread.sleep(100);
              } catch (InterruptedException e1) {
                // ignore
              }
              LOG.info("building outbound event #{}", i);
              try {
                // text/plain
                eventOutput.write(
                    new OutboundEvent.Builder()
                        .name("text-version")
                        .mediaType(MediaType.TEXT_PLAIN_TYPE)
                        .data(String.class, "msg " + i)
                        .id(Integer.toString(i))
                        .build());

                // application/json
                eventOutput.write(
                    new OutboundEvent.Builder()
                        .mediaType(MediaType.APPLICATION_JSON_TYPE) //
                        .data(EventModel.class, new EventModel("msg", i)) //
                        .build());
              } catch (IOException e) {
                LOG.error("ioexc:", e);
              }
            }
          } catch (Throwable t) {
            LOG.error("oops: " + t + " " + t.getMessage());
            t.printStackTrace();
          } finally {
            LOG.info(
                "done sending 10 items - connection will close from server side but browser reopens");
            try {
              eventOutput.close();
            } catch (IOException e) {
              // ignore...
            }
          }
        });
    return eventOutput;
  }
示例#2
0
 public void removeListener(int id, String key) {
   // TODO Close the event output stream.
   if (outputs.containsKey(id)) {
     EventOutput oput = outputs.get(id).remove(key);
     if (oput != null) {
       try {
         oput.close();
       } catch (IOException e) {
         System.out.println("State.java: Line 321 error");
       }
     }
   } else {
     // if
     SseBroadcaster bdcast = listeners.remove(key);
     if (bdcast != null) // Check if there is residue EventOutput in the
     // broadcaster
     {
       bdcast.closeAll();
     }
   }
   // Done
 }