Question

Among the COMET,SOCKETS,SSE i felt server sent events is easy to implement.
And i am using tomcat server so i used servlets to implement SSE.

But i am facing big problem here and searched a lot but i did not got any solution to it.

The problem is if you see the basic example at sever sent event

The output is repeating for every 4-seconds,can't we make it to change output in same line.
In detail:
After 4 seconds a new updated result is printing in next line of previous output,
i want it to be printed in the same line of previous output(over write on previous output)
and it should looks like a digital watch.

And my servlet code is like this what kind of changes i have to do.

  import java.io.IOException;
  import java.io.PrintWriter;
  import java.util.Date;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  @WebServlet("/SseServer")
  public class SseServer extends HttpServlet {
  private static final long serialVersionUID = 1L;
  protected void doGet(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
  }

  protected void doPost(HttpServletRequest request,
  HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/event-stream;charset=UTF-8");
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Connection", "keep-alive");

  PrintWriter out = response.getWriter();

  while (true) {
     out.print("id: " + "ServerTime" + "\n");
     out.print("data: " + new Date().toLocaleString() + "\n\n");
     out.flush();
     try {
            Thread.currentThread().sleep(4000);
       } catch (InterruptedException e) {
          e.printStackTrace();
          }
    }
 }

}

I thought using while loop make it as a repeated result.

GREAT THANKS FOR ANY HELP

Was it helpful?

Solution

The example you linked to uses the following code:

document.getElementById("result").innerHTML += event.data + "<br>";

So, it appends the new event data to the content of the result element. To replace it, just change it to

document.getElementById("result").innerHTML = event.data + "<br>";

In short, your question doesn't have anything to do with how you produce the event at server-side, but everything to do with how you consume the event, in the browser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top