Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5646

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T11:12:06+00:00 2024-11-27T11:12:06+00:00

Server Sent Events(SSE)

  • 60k

A server-sent event is when a web page automatically gets updates from a server. Traditionally, a web page has to send a request to the server to receive new data, then the server will send the response to the client. With server-sent events, a server can send new data to a web page at any time, by pushing messages to the web page.

If we are implementing SSE, we should keep the following two things in mind:

  1. A long-lived unidirectional communication exists (the communication happens between the server and the client)
  2. An HTTP connection only

A screen showing how unidirectional communication is happening form server to client

Communication flow between Server and Client using Server Sent Events. (Image Source: PubNub)

An HTTP request has been made. As long as we do not explicitly close this connection by doing some actions, such as changing the tab, this request will never terminate or close.

Every time there is new data, the server passes it on a regular interval over the same HTTP network, which is open.

Implementation

  1. Connection should be live
  2. The format in which data comes is event-stream

Example

We will understand the working of Server-Sent Events using an example. Suppose, we have a stock price listing platform where our stock prices are to be updated continuously. Now for this, we only need a unidirectional connection i.e. server to client, where our server would send the new prices to our clients whenever they are updated on our server.

  • We will create a normal HTML file and run the script in the script tag, where we will call (/see) and render the latest stock prices whenever the server updates them.
<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta http-equiv="X-UA-Compatible" content="IE=edge">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <title>SSE Test App</title> </head> <body>   <h1>In SSE App</h1>   <section style="height: 100px; width: 300px; background-color: antiquewhite;">   <ul style="list-style-type:disc">     <li> Stock1 Price : <span id="first-element"></span></li>     <li >Stock2 Price : <span id="second-element"></span></li>   </ul>   <div id="time"></div>    </section>    <script>     const eventSource = new EventSource('/sse')     eventSource.onmessage = (event)=>{       const resObject = JSON.parse(event.data)       const firstElement = document.getElementById('first-element')       firstElement.innerText = `${resObject.stock1Rate}`       const secondElement = document.getElementById('second-element')       secondElement.innerText = `${resObject.stock2Rate}`       const timeElement = document.getElementById('time')       timeElement.innerText = `${resObject.currentTime}`     }   </script> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

Note: I am adding the Backend code for better understanding.

  • Let us implement a simple Backend API to serve us stock prices at an interval of 5 seconds.
const express = require("express"); const {join} = require('node:path')  const PORT = 3010 const app = express()  app.use(express.static("public"));  app.get("/sse",(req, res)=>{   res.setHeader('Content-Type', 'text/event-stream');   res.setHeader('Connection','keep-live');   res.setHeader('Cache-Control', 'no-cache');    const intervalId = setInterval(() => {     const stock1Rate = Math.floor(Math.random() * 30000);     const stock2Rate = Math.floor(Math.random() * 40000);     const currentTime = new Date().toLocaleTimeString()     res.write(`data: ${JSON.stringify({currentTime,stock1Rate, stock2Rate})} 

`)   }, 5000);    req.on('close', ()=>{     clearInterval(intervalId)   })  })  app.get("/", (req, res) => {   res.sendFile(join(__filename, "/index.html")); });  app.listen(PORT,()=>{   console.log(`App is connected to ${PORT}`) }) 
Enter fullscreen mode Exit fullscreen mode

In the UI the stock prices will change after each 5sec –

stock price listing application

You can see how the response is received in the browser-

response received from server

Challenges that we may face while implementing

  1. Browser compatibility
  2. Connection limit
  3. Connection timeout
  4. Background tab behavior
  5. Resource utilization
  6. Load balancer
  7. Sticky connection
  8. Proxy/Firewall

I have tried to explain all the details of SSE that I know.

Thanks For Reading, Follow Me For More

expressjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.