title: How does Server-Sent-Events work
body: <p>I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed.</p>
  
  <p>I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!!</p>
  
  <ol>
  <li><p>What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now?</p></li>
  <li><p>What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? </p></li>
  <li><p>What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server?</p></li>
  <li><p>How to differentiate between GET and POST requests. Why did it choose GET?</p></li>
  <li><p>Is it too early to use SSE on Tomcat? Any performance issues?</p></li>
  </ol>
  
  <p>Here is the code for the curious,</p>
  
  <pre><code>@WebServlet("/TestServlet")
  public class TestServlet extends HttpServlet {
  
      public void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
  
          //content type must be set to text/event-stream
          response.setContentType("text/event-stream"); 
          //cache must be set to no-cache
          response.setHeader("Cache-Control", "no-cache");     
          //encoding is set to UTF-8
          response.setCharacterEncoding("UTF-8");
  
          PrintWriter writer = response.getWriter();
  
          for(int i=0; i&lt;10; i++) {
              System.out.println(i);
              writer.write("data: "+ i +"\n\n");
              writer.flush();
              try {
                  Thread.sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
          }
          writer.close(); 
      }
  }
  </code></pre>
  
  <p>Javascript on the page (I don't have anything else on the page),</p>
  
  <pre><code>&lt;button onclick="start()"&gt;Start&lt;/button&gt;
  
  &lt;script type="text/javascript"&gt;
      function start() {
          var eventSource = new EventSource("TestServlet");
          eventSource.onmessage = function(event) {
              console.log("data: "+event.data)
              document.getElementById('foo').innerHTML = event.data;
          };
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme??</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>What I have learned and learning is now documented in my blog - <a href="http://www.cs-repository.info/2016/08/server-sent-events.html" rel="noreferrer">Server Sent Events</a></p>