Welcome to our deep dive into HTML5 Server-Sent Events! This lesson is designed to help you understand and implement Server-Sent Events in your web projects, even if you're a beginner. Let's get started!
Server-Sent Events (SSE) is a one-way communication method between a web server and a web client (like a browser) over a long-lasting HTTP connection. It allows the server to push real-time updates to the client, making it perfect for applications requiring live updates, such as chat apps, news feeds, and real-time gaming.
To set up SSE on the server side, you'll need to use a server-side language like Node.js, PHP, or Python. For this tutorial, we'll use Node.js with the sse-server package.
First, install the sse-server package:
npm install sse-serverNext, create a new file called server.js and add the following code:
const http = require('http');
const sse = require('sse-server');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
const clientId = Date.now();
const sseServer = sse(res);
// Emit an event with a message every 3 seconds
setInterval(() => {
sseServer.emit('message', { data: `Message from server: ${clientId}` });
}, 3000);
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});This code sets up a simple server that listens for incoming connections, creates a new event stream for each connection, and emits a new message every 3 seconds.
Now let's create a simple HTML file that connects to our server and displays the received messages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Server-Sent Events Example</title>
</head>
<body>
<h1>Server-Sent Events Example</h1>
<div id="messages"></div>
<script>
const eventSource = new EventSource('http://localhost:3000');
eventSource.onmessage = function(event) {
const messagesDiv = document.getElementById('messages');
const newMessage = document.createElement('p');
newMessage.textContent = event.data;
messagesDiv.appendChild(newMessage);
};
</script>
</body>
</html>This HTML file sets up an EventSource object to connect to our server and listen for incoming messages. When a message is received, it appends the message to a <div> element on the page.
Now that you've seen how to set up Server-Sent Events, let's create a simple chat application. For this example, we'll create a simple chat room where users can send and receive messages in real-time.
This application will have two parts:
To keep things simple, we'll use Node.js and Express.js for the server, and plain HTML, CSS, and JavaScript for the client.
What is the main advantage of using Server-Sent Events over WebSockets for real-time communication in web applications?