Polling vs. Long Polling vs. WebSocket vs. Server-Sent Events

There are several techniques for real-time communication between clients and servers. Each of these techniques has its own characteristics and use cases. Polling and long polling are simple to use but they aren’t as efficient as WebSocket and Server-Side Events. Here’s how these techniques compare and contrast against each other.

Polling

  • Polling involves a client sending requests to the server at regular intervals to check if there are any updates.
  • On receiving the request, the server responds with new data if one is available or an empty response if no data has been updated.
  • You can leverage simple AJAX requests and page reloads to implement polling in your applications.
  • Clients repeatedly request updates even when there are none, resulting in unnecessary network traffic and increased server load.
  • This approach is suitable for scenarios where updates are infrequent or a real-time response is not a priority.

Long Polling

  • Long polling reduces unnecessary requests to the server and enables near real-time updates compared to regular polling.
  • Servers hold requests open until an update is available rather than responding immediately to a client request.
  • The server responds when an update is available. Then, the client sends a new request to keep the connection alive.
  • When no updates are available within a particular timeframe, the server responds with an empty response. The client sends a new request and continues listening.
  • Although long polling reduces the frequency of requests and enables a real-time response, it still involves frequent connections and overhead due to request/response cycles.

WebSocket

  • WebSocket enables communication between servers and consumers over a single, persistent, reliable, and full-duplex connection.
  • WebSocket is ideally suited for applications requiring continuous data transfers, such as chat applications and collaboration tools.
  • Due to server-side infrastructure requirements, WebSocket isn’t supported in all legacy or restricted environments such as older browsers and certain network configurations.

Server-Sent Events

  • SSE provides a lightweight, unidirectional approach to server-client communication over HTTP.
  • Contrary to WebSockets, communication between server and client in server-sent events runs in only one direction, from server to client.
  • SSE enables real-time updates without the complexity of WebSockets.
  • SSE is well suited for scenarios where communication is unidirectional, i.e., the server needs to forward updates to clients, such as news feeds, notifications, or real-time monitoring dashboards.

Use Cases

WebSockets provide bidirectional communication between a server and a client, which makes them suitable for real-time polling apps, chat apps, etc. Server-Sent Events support a unidirectional communication between client and server. This means that the messages are transmitted in single direction only, i.e., from server to client. They are often used for push notifications, news feeds, and other similar purposes.

Read about implementing Server side events.. more here

Getting all types that implement an interface

Using reflection, this is how we get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations.

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

Basically, the least amount of iterations will always be:

loop assemblies  
 loop types  
  see if implemented.

References

https://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface

When to use <> instead of ()

When we are suppose to use different parentheses in C#. When I run into a situation where i am trying to tell if i need to put <> or ().

The dumbed down version to explain is this;

() are for variables. <> are for types. If you have both, <> always comes first.

You would never has A(int). It would be A<int>. You’d also never have B<5>. It would always be B(5). And, rule two, you might have C<int>(5), but never C(5)<int>.

<> are used in generics.

Generics in C#

Generic is a type used to define a class, structure, interface, or method with placeholders to indicate that they can store or use one or more of the types. In C#, the compiler will replace placeholders with the specified type at compile time. We use generic frequently with collections.

Generics are useful for improving code reusability, type safety, and performance compared with non-generic types e.g. arraylist.

Here is a code sample;

//Generic example - using single generic type
public class Hospital<T>            //Here <T> is a a placeholder beside Hospital class
{
    private T Cases;                //Declared a variable named "Cases" of type T
    public Hospital(T value)        //Constructor take another variable named value
    {
        this.Cases = value;         //assinged received type to containting type "Cases"
    }

    public void Show()
    {
        Console.WriteLine(this.Cases);
    }
}

Let’s implement this in our .NET6 main class;

Console.WriteLine("Hello, World!");

//use Hospital class
Hospital<int> x = new Hospital<int>(100);       //replacing T with int
Hospital<string> y = new Hospital<string>("Hospital Cases");
x.Show();
y.Show();

We can use two generic types in a class;

//using two generic types
public class EliteHospital<T, U>            //Here <T> is a a placeholder beside Hospital class
{
    // PatientCount of type T
    public T? PatientCount {  get; set; }

    //Docotrs of U
    public U? Doctors { get; set; }  
}

This is how we can use this;

Console.WriteLine("Hello, World!");
//using EliteHospital class
EliteHospital<int, string> xx = new EliteHospital<int, string>();
xx.PatientCount = 100;
xx.Doctors = "Available";
Console.WriteLine(xx.PatientCount);
Console.WriteLine(xx.Doctors);

Console.WriteLine("Press any key to continue..");
Console.ReadKey();