<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Simranjit singh</title>
    <description>The latest articles on DEV Community by Simranjit singh (@simranjit884).</description>
    <link>https://dev.to/simranjit884</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F69842%2Fea8e331e-4752-4408-b8b1-523d39caea41.png</url>
      <title>DEV Community: Simranjit singh</title>
      <link>https://dev.to/simranjit884</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/simranjit884"/>
    <language>en</language>
    <item>
      <title>A Comprehensive Guide to Server-Sent Events (SSE) for Real-Time Web Applications</title>
      <dc:creator>Simranjit singh</dc:creator>
      <pubDate>Sun, 22 Sep 2024 18:54:54 +0000</pubDate>
      <link>https://dev.to/simranjit884/a-comprehensive-guide-to-server-sent-events-sse-for-real-time-web-applications-29e7</link>
      <guid>https://dev.to/simranjit884/a-comprehensive-guide-to-server-sent-events-sse-for-real-time-web-applications-29e7</guid>
      <description>&lt;h2&gt;
  
  
  Server-Sent Events (SSE)
&lt;/h2&gt;

&lt;p&gt;Server-Sent Events (SSE) is a standard allowing servers to push real-time updates to clients over a single, long-lived HTTP connection. Unlike WebSockets, which provide full-duplex communication, SSE is unidirectional, meaning data flows from the server to the client only. Here's a brief overview of how it works:&lt;/p&gt;

&lt;h2&gt;
  
  
  How SSE Works
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Client Requests Updates&lt;/strong&gt;: The client makes an HTTP request to the server, indicating it wants to receive updates.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server Keeps Connection Open&lt;/strong&gt;: The server keeps this connection open and sends updates as they become available.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Client Receives Updates&lt;/strong&gt;: The client listens for incoming messages and processes them as they arrive.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvfsa0ndhkirge2ymwkit.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvfsa0ndhkirge2ymwkit.png" alt="SSE working"&gt;&lt;/a&gt;&lt;em&gt;(image credits- geeksforgeeks.org)&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Features
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Unidirectional&lt;/strong&gt;: Data flows from server to client.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automatic Reconnection&lt;/strong&gt;: The client automatically attempts to reconnect if the connection is lost.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-Driven&lt;/strong&gt;: The server can send named events, allowing the client to handle different types of messages.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Long-Lived Connection&lt;/strong&gt;: It's a long live unidirectional communication.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Single HTTP Connection&lt;/strong&gt;: Uses a single HTTP connection.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Connection: keep-alive&lt;/strong&gt;: The connection is kept alive.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-Stream Type Data&lt;/strong&gt;: Data is sent in the event-stream format.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event Data Structure&lt;/strong&gt;: The event data structure includes &lt;code&gt;event | data | id&lt;/code&gt;, where &lt;code&gt;id&lt;/code&gt; is needed when there is a retry connection.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Use Cases
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Real-time notifications&lt;/strong&gt; (e.g., social media updates, news feeds)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Live sports scores&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Stock price updates&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Monitoring dashboards&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Example Implementation
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Server-Side (Node.js with Express)
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');&lt;br&gt;
const app = express();

&lt;p&gt;app.get('/events', (req, res) =&amp;gt; {&lt;br&gt;
    res.setHeader('Content-Type', 'text/event-stream');&lt;br&gt;
    res.setHeader('Cache-Control', 'no-cache');&lt;br&gt;
    res.setHeader('Connection', 'keep-alive');&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Send an initial message
res.write('data: Connected\n\n');

// Send updates every 5 seconds
const intervalId = setInterval(() =&amp;amp;gt; {
    res.write(`data: ${new Date().toISOString()}\n\n`);
}, 5000);

// Clean up when the client disconnects
req.on('close', () =&amp;amp;gt; {
    clearInterval(intervalId);
    res.end();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;});&lt;/p&gt;

&lt;p&gt;app.listen(3000, () =&amp;gt; {&lt;br&gt;
    console.log('Server running on &lt;a href="http://localhost:3000'" rel="noopener noreferrer"&gt;http://localhost:3000'&lt;/a&gt;);&lt;br&gt;
});&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Client-Side (HTML + JavaScript)&lt;br&gt;
&lt;/h3&gt;
&lt;br&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;
&amp;lt;html lang="en"&amp;gt;&lt;br&gt;
&amp;lt;head&amp;gt;&lt;br&gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;&lt;br&gt;
    &amp;lt;title&amp;gt;SSE Example&amp;lt;/title&amp;gt;&lt;br&gt;
&amp;lt;/head&amp;gt;&lt;br&gt;
&amp;lt;body&amp;gt;&lt;br&gt;
    &amp;lt;h1&amp;gt;Server-Sent Events Example&amp;lt;/h1&amp;gt;&lt;br&gt;
    &amp;lt;div id="events"&amp;gt;&amp;lt;/div&amp;gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;amp;lt;script&amp;amp;gt;
    const eventSource = new EventSource('/events');

    eventSource.onmessage = function(event) {
        const newElement = document.createElement("div");
        newElement.textContent = `New event: ${event.data}`;
        document.getElementById("events").appendChild(newElement);
    };

    eventSource.onerror = function() {
        console.error("EventSource failed.");
    };
&amp;amp;lt;/script&amp;amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&amp;lt;/body&amp;gt;&lt;br&gt;
&amp;lt;/html&amp;gt;&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Explanation&lt;br&gt;
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Server-Side&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The server sets the appropriate headers to indicate an SSE connection.&lt;/li&gt;
&lt;li&gt;It sends an initial message and then periodically sends updates.&lt;/li&gt;
&lt;li&gt;It handles client disconnection by cleaning up resources.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Client-Side&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The client creates an &lt;code&gt;EventSource&lt;/code&gt; object to listen for updates from the server.&lt;/li&gt;
&lt;li&gt;It handles incoming messages by appending them to the DOM.&lt;/li&gt;
&lt;li&gt;It handles errors, such as connection failures.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Challenges
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Browser Compatibility&lt;/strong&gt;: Not all browsers support SSE, which can limit its use.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Connection Limit&lt;/strong&gt;: Browsers and servers may limit the number of open connections.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Connection Timeout&lt;/strong&gt;: Long-lived connections can time out, requiring reconnection.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Background Tab Behavior&lt;/strong&gt;: Browsers may throttle or suspend connections in background tabs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Utilization&lt;/strong&gt;: Keeping many connections open can consume server resources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Load Balancer&lt;/strong&gt;: Load balancers need to support long-lived connections.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sticky Connection&lt;/strong&gt;: Ensuring the same client connects to the same server instance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Proxy/Firewall&lt;/strong&gt;: Proxies and firewalls may interfere with long-lived connections.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing&lt;/strong&gt;: Simulating and testing long-lived connections can be challenging.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Broadcasting&lt;/strong&gt;: Efficiently broadcasting messages to many clients can be complex.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In short, SSE is a simple and efficient way to implement real-time updates in web applications where only the server needs to push data to the client.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>systemdesign</category>
      <category>javascript</category>
      <category>mern</category>
    </item>
    <item>
      <title>Understanding Short Polling: A Simple Approach to Client-Server Communication</title>
      <dc:creator>Simranjit singh</dc:creator>
      <pubDate>Sun, 22 Sep 2024 16:17:03 +0000</pubDate>
      <link>https://dev.to/simranjit884/understanding-short-polling-a-simple-approach-to-client-server-communication-3ldm</link>
      <guid>https://dev.to/simranjit884/understanding-short-polling-a-simple-approach-to-client-server-communication-3ldm</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is a short polling?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Short polling is a technique used in client-server communication where a client repeatedly sends requests to a server at regular short intervals to check for updates or new data. It's called "short polling" because of the relatively brief delay between each request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt; - It is commonly used in scenarios where real-time updates are not critical, such as periodic data updates or system health checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How short polling works?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Request Initiation: The client sends a request to the server.&lt;/li&gt;
&lt;li&gt;Immediate Response: The server processes the request and responds immediately, even if there is no new data.&lt;/li&gt;
&lt;li&gt;Repeat Requests: The client waits for a predetermined interval before sending another request.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5j0yhr4nqvg6zb7wygr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe5j0yhr4nqvg6zb7wygr.png" alt="Short polling Workings" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Easy to Implement&lt;/strong&gt;: Simple logic for sending requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Independent Requests&lt;/strong&gt;: Each request is independent, which can reduce server memory usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Inefficient for Real-Time Needs&lt;/strong&gt;: High frequency of requests can lead to unnecessary network traffic and server load if updates are infrequent, as the client is constantly polling the server regardless of whether new data is available.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Latency&lt;/strong&gt;: The client may not receive updates immediately, as it relies on the polling interval.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Problem with scale&lt;/strong&gt;: As the number of users grows, the number of network requests will get increased leading to the point number 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Below is an example of how you can implement short polling using JavaScript on the client side and Node.js with Express on the server side.&lt;/p&gt;

&lt;h3&gt;
  
  
  Server-Side (Node.js with Express)
&lt;/h3&gt;

&lt;p&gt;First, set up a simple Express server that responds to client requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// server.js
const express = require('express');
const app = express();
const port = 3000;

let data = { message: "Hello, World!" };

app.get('/poll', (req, res) =&amp;gt; {
    res.json(data);
});

app.listen(port, () =&amp;gt; {
    console.log(`Server running at http://localhost:${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Client-Side (HTML + JavaScript)
&lt;/h3&gt;

&lt;p&gt;Next, create an HTML file with JavaScript to repeatedly send requests to the server at regular intervals.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="UTF-8"&amp;gt;
    &amp;lt;title&amp;gt;Short Polling Example&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Short Polling Example&amp;lt;/h1&amp;gt;
    &amp;lt;div id="data"&amp;gt;&amp;lt;/div&amp;gt;

    &amp;lt;script&amp;gt;
        function fetchData() {
            fetch('http://localhost:3000/poll')
                .then(response =&amp;gt; response.json())
                .then(data =&amp;gt; {
                    document.getElementById('data').innerText = data.message;
                })
                .catch(error =&amp;gt; console.error('Error fetching data:', error));
        }

        // Poll the server every 5 seconds
        setInterval(fetchData, 5000);

        // Initial fetch
        fetchData();
    &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Explanation
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Server-Side&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The server listens on port 3000 and responds to GET requests at the &lt;code&gt;/poll&lt;/code&gt; endpoint with a JSON object containing a message.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Client-Side&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The client uses the &lt;code&gt;fetch&lt;/code&gt; API to send a GET request to the server every 5 seconds using &lt;code&gt;setInterval&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The response is parsed as JSON and the message is displayed in a &lt;code&gt;div&lt;/code&gt; with the ID &lt;code&gt;data&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;An initial fetch is performed to display data immediately when the page loads.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Running the Example
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Start the Server&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Save the server code in a file named &lt;code&gt;server.js&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;npm init -y&lt;/code&gt; to create a &lt;code&gt;package.json&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;npm install express&lt;/code&gt; to install Express.&lt;/li&gt;
&lt;li&gt;Start the server with &lt;code&gt;node server.js&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Open the Client&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Save the client code in an HTML file (e.g., &lt;code&gt;index.html&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Open the HTML file in a web browser.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You should see the message "Hello, World!" displayed on the web page, and it will be updated every 5 seconds as the client polls the server. You can modify the server code to change the data and see how the client updates in real-time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In summary&lt;/strong&gt;, while short polling is a useful technique for real-time updates when you don’t need to handle a high volume of users or need immediate real-time data, it is generally less efficient compared to long polling, WebSockets, or Server-Sent Events (SSE), which are more preferred for the scalable solutions.&lt;/p&gt;




</description>
      <category>javascript</category>
      <category>systemdesign</category>
      <category>frontend</category>
    </item>
  </channel>
</rss>
