I'm trying to implement Server Sent Events using Spring SseEmitter as described in this Youtube video.
I'm able to initiate the event stream and receive the data from the server sent event.
However, I can see multiple EventStream
type requests fired from the client and arriving at the server. The way I understand it, EventSource
should send a single HTTP
request and then should maintain a half duplex
connection from the server, using which server sends the events to the client.
Why is it then sending requests at regular interval ? Isn't it then like polling instead of a half duplex connection ?
Bellow is the code that I'm using.
Server code
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder;
@RestController
public class TestService {
private List<SseEmitter> subscriberList = Collections.synchronizedList(new ArrayList<>());
@RequestMapping("inbox")
public SseEmitter inbox() {
SseEmitter subscriber = new SseEmitter();
subscriberList.add(subscriber);
subscriber.onCompletion(() -> {
subscriberList.remove(subscriber);
System.out.println("Removed the completed event emitter");
});
System.out.println("Subscriber arrived");
return subscriber;
}
@RequestMapping("message")
public String message(@RequestParam("message") String message) {
System.out.println("SubscriberList size " + subscriberList.size());
for(SseEmitter subscriber : subscriberList) {
try {
SseEventBuilder eventBuilder = SseEmitter.event().name("group1").data(message);
subscriber.send(eventBuilder);
} catch (Exception e) {
e.printStackTrace();
}
};
return message;
}
}
Client code
$(function () {
console.log("Started");
var eventSource = new EventSource("/inbox");
eventSource.addEventListener('error', function(e) {
if (e.currentTarget.readyState == EventSource.CLOSED) {
console.log("Connection is closed")
} else {
source.close();
console.log("Closing connection");
}
});
eventSource.addEventListener("group1", function (event) {
console.log(event.data);
document.querySelector("body").innerHTML += "<div>" + event.data + "</div>";
});
});
Bellow is the client network tab screenshot from chrome
Here's server side log
Subscriber arrived
Removed the completed event emitter
Subscriber arrived
Removed the completed event emitter
Subscriber arrived
Removed the completed event emitter
Subscriber arrived
Removed the completed event emitter
Subscriber arrived
Removed the completed event emitter
Subscriber arrived
Removed the completed event emitter
Subscriber arrived