0

I have a Java Web server using Spring Framework and I want to use Server Sent Events to send notifications to the web client at each second.

My Controller for these notifications looks like this:

@Controller
public class NotificationController {

    private static final String REST_PREFIX = "/rest/notifications";

    @RequestMapping(value = {REST_PREFIX}, method = {RequestMethod.GET})
    synchronized public void getMonitoringNotifications(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/event-stream;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Connection", "keep-alive");

        try {
            PrintWriter out = response.getWriter();
            int i = 0;

            while (true) {
                out.print("id: " + "ServerTime" + "\n");
                out.print("data: " + (i++) + "\n\n");
                out.flush();

                Thread.currentThread().sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

My problem is that instead of receiving each notification after 1 second, the client waits for all notifications to be sent. If I try to send a number of notifications, let's say 30, on the client I will receive them all at the end.

My client is a simple as it only listens to the specific endpoint to get notifications:

<!DOCTYPE html>
<html>
<body>
 <h1>Notification received  : </h1>

 <div id="ServerTime"></div>

 <script>
  if (typeof (EventSource) !== "undefined") {
   var source = new EventSource("https://10.241.53.185/rest/notifications");
   source.addEventListener('message', function(event) {
    console.log(event.data);
   });
  } else {
   document.getElementById("ServerTime").innerHTML = "Working, processing, getting info....";
  }
 </script>

</body>
</html>

Could you please help me with this issue?

Thanks

2
  • 1
    That is clearly NOT the way to send information to the client. Use an SseEmitter or a StreamingResponseBody as the result. Commented Dec 14, 2016 at 13:20
  • Thanks for the information. I have also found the problem with my code as i needed to write to the printer in a different thread. Commented Dec 14, 2016 at 13:37

1 Answer 1

2

You need to use SseEmitter to send events. See Server-Sent Events with Spring (blog).

You also should send the events from a separate thread (letting the request thread return).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that really helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.