Spring SSEEmitter Getting Completed Mid-way
<p>I am new to Server Sent Events but not to Spring.
Have made a controller which gets triggered from a button on the UI which initiates SSEEmitter and passed that to another thread which in loop sends message to UI after each 4 seconds. 
SO far i am running a loop of 10 which sleeps for 4 seconds each but suddenly around iteration of 6 or 7th loop, I get exception "Exception in thread "Thread-4" java.lang.IllegalStateException: ResponseBodyEmitter is already set complete"..</p>

<p>Hence, event source again re-establishes the connection i.e. calls the controller method again which certainly i do not want.</p>

<p>I am here trying a simple thing.. User subscribes by clicking on the button.. 
Server send response 10 or 20 whatever times to the browser. And as far as I think this is what SSE created for.</p>

<p>Code below.:</p>

<pre><code>@RequestMapping("/subscribe")
public SseEmitter subscribe() {
    SseEmitter sseEmitter = new SseEmitter();
    try {
        sseEmitter.send("Dapinder");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Runnable r = new AnotherThread(sseEmitter);
    new Thread(r).start();
    return sseEmitter;
}
</code></pre>

<p>public class AnotherThread implements Runnable {</p>

<pre><code>private SseEmitter sseEmitter;

public AnotherThread(SseEmitter sseEmitter) {
    super();
    this.sseEmitter = sseEmitter;
}

@Override
public void run() {
    SseEventBuilder builder = SseEmitter.event();
    builder.name("dapEvent");
    for (int i = 0; i &lt; 10; i++) {
        builder.data("This is the data: " + i +" time.");
        try {
            //sseEmitter.send(builder);
            sseEmitter.send("Data: "+i);
            //sseEmitters.get(1L).send("Hello");
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    sseEmitter.complete();
}

public SseEmitter getSseEmitter() {
    return sseEmitter;
}

public void setSseEmitter(SseEmitter sseEmitter) {
    this.sseEmitter = sseEmitter;
}
</code></pre>

<p>}</p>

<pre><code>function start() {
    var eventSource = new EventSource("http://localhost:8080/HTML5SSE/springSSE/subscribe"); //  /springSSE/connect
      eventSource.onmessage = function(event) {
        document.getElementById('foo').innerHTML = event.data;
    };

}


&lt;button onclick="start()"&gt;Subscribe&lt;/button&gt;
</code></pre>