Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Sse in HTML

Sse in HTML

? SSE (Server-Sent Events) in HTML

Server-Sent Events (SSE) allow a web page to get automatic updates from a server via a persistent HTTP connection. It's a simple way to push real-time data from server to client.


How SSE Works

  • Client opens a connection to the server.

  • Server keeps sending updates as new events happen.

  • Client receives and processes these events automatically.


Basic Example of SSE

1. HTML + JavaScript (Client Side)

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8" />  <title>SSE Example</title></head><body>  <h2>Server-Sent Events Example</h2>  <div id="events"></div>  <script>    if (typeof(EventSource) !== "undefined") {      const source = new EventSource("server.php"); // URL of the SSE server      source.onmessage = function(event) {        const newElement = document.createElement("p");        newElement.textContent = "New message: " + event.data;        document.getElementById("events").appendChild(newElement);      };      source.onerror = function() {        console.error("EventSource failed.");      };    } else {      document.getElementById("events").textContent = "Sorry, your browser does not support SSE.";    }  </script></body></html>

2. Server-Side Example (PHP)

<?phpheader('Content-Type: text/event-stream');header('Cache-Control: no-cache');$time = date('r');echo "data: The server time is: {$time}\n\n";flush();

Key Points

  • The server must send data in a special format: lines starting with data: followed by event data and double newline \n\n to signal event end.

  • Client uses JavaScript's EventSource object to listen to the stream.

  • Works over regular HTTP, unlike WebSockets (which are full-duplex).


When to Use SSE?

  • Live news feeds

  • Stock price updates

  • Real-time notifications

  • Social media feeds


Want help writing SSE code in other server languages or examples with reconnection handling?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql