๐Ÿš€ Server-Sent Events - One Way Messaging๐Ÿš€


View on LinkedIn


A server-sent event is when a web page automatically gets updates from a server, a unidirectional "push".

While other methods like Polling, Webhooks, Websockets, and Long live connections exist, SSEs stand out as a dedicated channel for sending updates to the client. ๐Ÿ”„

Examples? Think stock price updates, news feeds, sport results, device monitoring - SSEs are your go-to solution! ๐Ÿ’ก


The HTML5 spec calls it "EventSource".



Implementation Guide:


client side :


1. Create a new EventSource object, and specify the URL of the resource

2. the onmessage event occurs each time an update is received, you can put your logic here


<JS>


var source = new EventSource("sse_url");

source.onmessage = function(event) {

document.getElementById("result").innerHTML = event.data;

};



server side:


1. Set the "Content-Type" header to "text/event-stream"

2. Specify that the page should not cache

3. Output the data to send (Always start with "data: ")

4. Flush the output data back to the web page



<?php

header('Content-Type: text/event-stream');

header('Cache-Control: no-cache');


$time = date('r');

echo "data: The server time is: {$time}\n\n";

flush();

?>



Code examples referred from here

You can also check out this article for a python server implementation using generators