Server-Sent Events

 Server-Sent Events


Server-Sent Events allow the server to send data to the client over a long-lived HTTP connection. This can be useful for real-time updates and notifications. The client can receive the data using the EventSource API.

Here's an example of how to use Server-Sent Events:



// server code

const http = require('http');

const server = http.createServer(function(req, res) {

  res.writeHead(200, {'Content-Type': 'text/event-stream'});

  setInterval(function() {

    res.write('data: ' + new Date().toLocaleTimeString() + '\n\n');

  }, 1000);

});

server.listen(3000);


// client code

const source = new EventSource('/sse');

source.onmessage = function(event) {

  console.log(event.data); // "data: 12:34:56 PM\n\n"

};

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...