Server Side Events


Server Side Events is so powerful for real-time processing yet so simple to use it is scary.
Server Side Events(SSE) is implemented in html and backed by server side code. Most anyone even asking the question(how to use SSE) knows what to do with an ajax request (get or post).
var source = new EventSource("StartEvent");
source.onmessage = function(event) {
console.log(event.data) // see your event data
$.get("SecondHandler", function( data ) {
$("#chat-first").append(data)
});
};

The EventSource points to a Event generated by the server. To keep things simple think of it as a task that will return something if a file comes into existance. Ill let you imagine how that goes. You will at least return a content type return "text/event-stream" plus something like data: fileexists.
Where only the content type and the "data:" are required You also need to have crlf+crlf at end of the data statement.
Hence, allow my over simplificaion so I don't need to put up 25 languages like I have written an API.
response.contenttype="text/event-stream"
if file exits then
return "data: (yourdata)"+crlf+crlf
else
return ""
That will be enough to trigger onmessage. Which is the goal, this article is trying to get you to. You may need to actually see your event.data once to appreciate the flow. You will notice we dont see events like setTimeout call to function would give (polling).
The next thing you do is respond to your event, it could parse event.data for multiple events here or in your code where-ever your feel the most comfortable but I found that there cannot be more than one event source. Another thing, I derived through hacking (am I wrong?)
ajax to a handler as shown above and you have got it. I would use the handler to at least delete the file.
Warning: I did not cover the subject of requiring http 2. It is not all that important because you probably have what you need to make this work. That is what matters. But, if for some reason, it does not work, then upgrade your web server or browser before you give up. SSE provides power unseen since the days when we could not format html without using tables.
Most programmers do not like the use of "+" when it comes to string concation. You can leave a comment and tell me all about it. At least Ill know someone read this besides me. I like some of the other articles out there. They got me started, but they did not mention the termination string requirement, or made the mention of it so small I had to hack until I found it. It became obvious then. It is super to know this came as a result of http 2 but what is more important is the termination string. So I will focus on that. Do it.
I like a full working demos too. So view-source on the demo at Chatmod.Online is my chat site where I use this with AI even though the AI call can be direct. Maybe I'll post something on there that isn't AI but that is kinda the point of the site.