<?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: Husain Sayyed</title>
    <description>The latest articles on DEV Community by Husain Sayyed (@syedrasique718).</description>
    <link>https://dev.to/syedrasique718</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%2F2481682%2F728fb5cb-30e8-4256-a1dc-5fafe6561cc8.png</url>
      <title>DEV Community: Husain Sayyed</title>
      <link>https://dev.to/syedrasique718</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/syedrasique718"/>
    <language>en</language>
    <item>
      <title>Server-Sent Events: A Lightweight Alternative to WebSockets</title>
      <dc:creator>Husain Sayyed</dc:creator>
      <pubDate>Wed, 27 Nov 2024 07:31:00 +0000</pubDate>
      <link>https://dev.to/syedrasique718/server-sent-events-a-lightweight-alternative-to-websockets-100h</link>
      <guid>https://dev.to/syedrasique718/server-sent-events-a-lightweight-alternative-to-websockets-100h</guid>
      <description>&lt;p&gt;&lt;em&gt;I am going to write a few Blogs on Backend Communication Patterns, While this being my first one.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As a Developer, I am sure that one of the most use backend communication patterns is HTTP request. we use them all the time when we need the data from the server.&lt;/p&gt;

&lt;p&gt;But with HTTP request calls you can only get data if you ask for it, means that once you request for any data, the server returns the response and close the connection.&lt;/p&gt;

&lt;p&gt;Now What if you need the data continuously, like a live match score update. What will you do here ? I am sure most people would say &lt;code&gt;WebSockets&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The problem with WebSockets is that it’s Bi-Directional Communication Protocol, indeed it has it use cases like Chat Applications, but not every use case needs Bi-Directional Communication, What if we only need Server to sent us real time Data ?&lt;/p&gt;

&lt;p&gt;Here, is the perfect scenario to use Server Sent Events.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;So, What is Server Sent Events ?&lt;br&gt;
&lt;strong&gt;Server Sent Events (SSE)&lt;/strong&gt; is communication done over HTTP protocol. It allows the server to send data to the client once an initial connection has been established.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fqlceix4tanfytf76px7y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fqlceix4tanfytf76px7y.png" alt="Connection Flow For SSE" width="800" height="618"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How do you Setup and Work with &lt;strong&gt;Server Sent Events&lt;/strong&gt; ?&lt;/p&gt;

&lt;p&gt;As with any normal HTTP request, SSE connection must also initiated by Client ( Browser ). There are few configuration you must do on the Server as well as for Client side code.&lt;/p&gt;

&lt;p&gt;Your 1st step would be to set the right Headers in HTTP request.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Set &lt;code&gt;Content-Type&lt;/code&gt; header to &lt;code&gt;text/event-stream&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set &lt;code&gt;Cache-Control&lt;/code&gt; header to &lt;code&gt;no-cache&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Connection&lt;/code&gt; header to &lt;code&gt;keep-alive&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fnrzwqd5n2b3wxidgbttn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fnrzwqd5n2b3wxidgbttn.png" alt="Example of Request and Response Headers." width="598" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While most of the frameworks do this by Default, but it’s nice to know how it is different from normal HTTP requests.&lt;/p&gt;

&lt;p&gt;Your 1st step would be to return each data from the backend in the following format :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;event — A string specifying the type of data, by default the value is message and you can listen on the eventSource.onmessage . If you decided to use any custom string, then you can listen on that event using addEventListener("MyCustomEvent", (event) =&amp;gt; {}).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;data — Pass your own custom data, can be anything, String or JSON encoded Object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;id — Create a unique Id from the backend, Maybe a incremental value.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.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%2Fmsezyt6it8795r9egl04.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2Fmsezyt6it8795r9egl04.gif" alt="Streaming the event data." width="800" height="250"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s Dive into Implementation part, I will be using Spring Boot for Backend Server and Angular for the FrontEnd.&lt;/p&gt;

&lt;p&gt;I am using Spring Boot since that is what I am familiar with, But you find the setup easily in your programming language. You can refer to the implementation in PHP &lt;a href="https://github.com/mdn/dom-examples/blob/main/server-sent-events/sse.php" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// using Fiegn Client for https://random-data-api.com/api/v2/
private final RandomUserFiegnClient randomUserFiegnClient;

@GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux&amp;lt;ServerSentEvent&amp;lt;String&amp;gt;&amp;gt; streamEvents() {
    return Flux.interval(Duration.ofSeconds(3))
           .publishOn(Schedulers.boundedElastic())
           .handle((sequence, sink) -&amp;gt; sink.next(ServerSentEvent.&amp;lt;String&amp;gt;builder()
                .id(String.valueOf(sequence))
                .event("message")
                .data(randomUserFiegnClient.getRandomUser().toString())
                .build()));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s understand a main parts here,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;produces = MediaType.TEXT_EVENT_STREAM_VALUE&lt;/code&gt; Basically set the Content-Type header to text/event-stream.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Flux.interval(Duration.ofSeconds(3))&lt;/code&gt; for every 3 seconds send the latest data back to client.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;data(randomUserFiegnClient.getRandomUser().toString())&lt;/code&gt; use random data API to return Random User information.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once this is setup, let’s setup Client side code as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Create an Event Source Object.
// The server-sent event API is contained in the EventSource interface.
const eventSource = new EventSource('http://localhost:8080/sse');

// Once created, Listen on OnOpen Event.
// This will let you if connection to backend is established or Not.
eventSource.onopen = (e) =&amp;gt; {
  console.log("The connection has been established.");
  // Add Your Business Logic Here.
  eventSource.onmessage = (event) =&amp;gt; {
    console.log(event.lastEventId); // unique event id from the server.
    console.log(event.type); // type of event
    console.log(event.data); // actual Data.
  };
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code is a basic setup, Of course based on your use case you have to modified it a lot. Let’s See how you can check for Connection Errors or Closed the connection if you are done.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;eventSource.onerror = (err) =&amp;gt; {
  // Maybe display a generic error message, and helpful for developer to debug.
  console.error("EventSource failed:", err);
};

// Let's say you are now done, and You want to close the connection.
eventSource.close();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure you are closing the connection, to prevent overload on servers.&lt;br&gt;
Let’s see the final Implementation :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F8fin9jhekn41a6zr8kgd.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F8fin9jhekn41a6zr8kgd.gif" alt="Implementation of Server Sent Events." width="1668" height="588"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And now for the closing remarks, when you should use &lt;code&gt;Server Sent Events (SSE)&lt;/code&gt; for 1-way data streaming.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Live Match Score Updates, Notifications, or Dashboards.&lt;/li&gt;
&lt;li&gt;Tracking System.&lt;/li&gt;
&lt;li&gt;Or If you just want the server to sent you the real-time data, and there will no communication from the client side.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One Last point, remember it’s Limitation :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Number of Connections — If you are not using HTTP/2, then the maximum connection you can setup is 6. For Chrome check the issue here and firefox here.&lt;/li&gt;
&lt;li&gt;Data Format — You can only send UTF-8 messages, unfortunately Binary Data is not supported.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;em&gt;Have you implemented Server-Sent Events in your projects? Or do you have thoughts on real-time communication patterns? Share your experiences, questions, or feedback in the comments below. Let’s continue the conversation and learn from each other’s journeys!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Stay tuned as we dive into more backend communication strategies, uncovering the strengths and nuances of each to help you make informed choices for your applications.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>serversentevents</category>
      <category>sse</category>
      <category>eventstreaming</category>
    </item>
    <item>
      <title>toList() vs. Collectors.toList(): What’s the Difference in Java?</title>
      <dc:creator>Husain Sayyed</dc:creator>
      <pubDate>Mon, 25 Nov 2024 15:17:58 +0000</pubDate>
      <link>https://dev.to/syedrasique718/tolist-vs-collectorstolist-whats-the-difference-in-java-ppi</link>
      <guid>https://dev.to/syedrasique718/tolist-vs-collectorstolist-whats-the-difference-in-java-ppi</guid>
      <description>&lt;p&gt;&lt;em&gt;Heyy, I’m Husain Sayyed, a software engineer passionate about exploring and sharing knowledge in Java, Spring Boot, and beyond. With several years of experience in development, I’ve decided to channel my learnings into blogging.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This is my first blog, and I’d love to hear your feedback to improve and make this journey engaging for all of us.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Today, I’ll be diving into the subtle but important differences between &lt;code&gt;toList()&lt;/code&gt; and &lt;code&gt;Collectors.toList()&lt;/code&gt; in Java — two methods that often puzzle developers when working with streams.&lt;/p&gt;

&lt;p&gt;While these two methods might seem similar at first glance, their underlying implementations are quite different. Overlooking these differences can lead to subtle issues, such as unintended mutations or errors in your code.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;toList()&lt;/code&gt; method is a new addition introduced in Java 16 while &lt;code&gt;Collectors.toList()&lt;/code&gt; is a part of the Java Stream API since Java 8.&lt;/p&gt;

&lt;p&gt;The key difference between both of them is &lt;code&gt;Mutability&lt;/code&gt; . One method creates an Unmodifiable List while another create a Modifiable List.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Collectors.toList()&lt;/code&gt; creates an Modifiable List, that you can use to add , update or remove elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;String&amp;gt; list = Stream.of("A", "B", "C").collect(Collectors.toList());
list.add("D"); // Modifiable list
System.out.println(list); // prints [A, B, C, D]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;toList()&lt;/code&gt; creates an Unmodifiable List for you, see below :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;String&amp;gt; list = Stream.of("A", "B", "C").toList();
System.out.println(list); // prints [A, B, C] so works fine

// but the moment you try to mutate the list, it will fail.
list.add("D"); // Throws Unsupported Error
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope you never got to see this error, but If you see this later. Now you know what to do.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F3fnt8b75de2ddscym6di.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F3fnt8b75de2ddscym6di.png" alt="Throws Unsupported Operation Exception" width="720" height="139"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want to dive deep, You can see the internal implementation throws UnsupportedOperationException (uoe) in ImmutableCollections.java from java.util package.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.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%2F5qsum93skd0w4q75r97z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.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%2F5qsum93skd0w4q75r97z.png" alt="Internal Implementation of AbstractImmutableCollection" width="720" height="288"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So, when to use which methods, Use&lt;br&gt;
&lt;code&gt;ToList()&lt;/code&gt; when immutability is required, or You know you will not mutate this list, or for thread safety or maintaining integrity.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Collectors.toList()&lt;/code&gt; when you need a list that can be modified later.&lt;/p&gt;

&lt;p&gt;_Understanding the subtle differences between &lt;code&gt;toList()&lt;/code&gt; and &lt;code&gt;Collectors.toList()&lt;/code&gt; can help you write more intentional and efficient Java code. While both have their place, the choice depends on your specific needs regarding mutability and Java version compatibility.&lt;/p&gt;

&lt;p&gt;I hope you found this blog helpful and that it added some clarity to your understanding of &lt;code&gt;toList()&lt;/code&gt; and &lt;code&gt;Collectors.toList()&lt;/code&gt; in Java. Thanks for reading, and I’d love to hear your thoughts!_&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
