Implementation of an SSE server in Java cannot keep persistent connection

762 views Asked by At

I have made a simple HTTP server in Java for sending events with MIME type text/event-source to a JS script that uses EventSource. But the problem is that EventSource is closing the connections as soon as it is opened, causing repeated connections to the server.

Here is the request from EventSource:

Accept:text/event-stream
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
DNT:1
Host:localhost:8080
Pragma:no-cache
Referer:http://localhost:8080/dispenser/ui/app/index.html
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36

Here is the response from my Java server:

Cache-Control:no-cache
Content-Type:text/event-stream;charset=UTF-8
Date:Fri Jun 05 11:01:39 NPT 2015
Server:MY-SERVER/1.0

Here is the JS code:

var eventSource = new EventSource('/my-event-source');
    eventSource.addEventListener('event1', function (e) {
        // ...
    });
    eventSource.addEventListener('event2', function (e) {
        // ...
    });

Chromium developer tool log:

services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
services    GET 200 text/event-stream   Other   280 B   2 ms
...

What do I seem to have missed?

UPDATE: I had incorrectly implemented "keep alive" feature in my HTTP server, that is why the connection was being closed.

0

There are 0 answers