.NET HELP

Socket io .NET (How It Works For Developers)

Published September 29, 2024
Share:

The Socket.IO server stands as a robust library, facilitating real-time, bidirectional, and event-driven communication. It's widely used in web applications for tasks such as chat applications, live updates, and collaborative platforms. While Socket.IO is typically associated with JavaScript, it can also be used effectively on client-side with C#. Sometimes the client may be a web browser. In this article, we'll explore how to set up and use a Socket.IO client in a C# environment. We'll go through some basic examples and conclude with the benefits and potential use cases.

Methods to Establish Socket.IO Connections

The Socket.IO connection can be established with different low-level transports:

  • HTTP long-polling
  • Web Sockets

    • Web Transport

Socket io .NET (How It Works For Developers): Figure 1 -                                                              Client-Server communication application

Creating a Console Project in Visual Studio 2022

Open Visual Studio, and select Create a new project in the Start window.

Socket io .NET (How It Works For Developers): Figure 2 - Screenshot that shows the Create a new project window.

To create a console application in Visual Studio 2022, launch Visual Studio and select "Create a new project" from the start window. Choose the "Console App" template, configure the project with a name and location, and ensure .NET 6.0 is selected.

What is Socket.IO?

Socket.IO, a JavaScript library, empowers web clients and servers to engage in real-time communication. It consists of two parts:

Parts of Socket IO

  • Client-side library: Runs in the browser.
  • Server-side library: Runs on Node.js.

Install the Necessary Packages

To use Socket.IO for .NET applications in Visual Studio, you'll need a compatible server implementation. One such implementation is the SocketIoClientDotNet for .NET, which allows a Socket IO client to connect to a Socket.IO from a C# application.

First, install the required NuGet packages. You can do this via the Package Manager Console or by adding the references to your project file.

Install-Package SocketIoClientDotNet
Install-Package SocketIoClientDotNet
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package SocketIoClientDotNet
VB   C#

Screenshot of the SocketIoClientDotNet package

Socket io .NET (How It Works For Developers): Figure 3 - Install Socket.IO for NET using the Manage NuGet Package for Solution by searching "SocketIoClientDotNet" package name in the search bar of NuGet Package Manager, then select the project and click on the Install button.

Executing this command will incorporate the Socket.IO client library into your .NET project, empowering your C# application to connect with a Socket.IO server, facilitating communication between users and the system.

Creating Socket.IO

Before diving into the C# client, let’s set up a basic example of Socket IO using .NET Core Console App in Visual Studio. This will help us test the client implementation.

Creating Server Implementations

The following code sets up a basic Socket.IO server in C# that listens for client connections on port 3000. When a client sends a message, the logs the message and responds back to the client, confirming receipt.

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Connect to the Socket.IO server
            var socket = IO.Socket("http://localhost:3000");
            // Listen for the "connect" event
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Console.WriteLine("Connected to the server!");
                // Emit a message to the server
                socket.Emit("message", "Hello from C# client!");
                // Listen for messages from the server
                socket.On("message", (data) =>
                {
                    Console.WriteLine("Message from server: " + data);
                });
            });
            // Listen for the "disconnect" event
            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                Console.WriteLine("Disconnected from the server!");
            });
            // Keep the console window open
            Console.ReadLine();
        }
    }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Connect to the Socket.IO server
            var socket = IO.Socket("http://localhost:3000");
            // Listen for the "connect" event
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Console.WriteLine("Connected to the server!");
                // Emit a message to the server
                socket.Emit("message", "Hello from C# client!");
                // Listen for messages from the server
                socket.On("message", (data) =>
                {
                    Console.WriteLine("Message from server: " + data);
                });
            });
            // Listen for the "disconnect" event
            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                Console.WriteLine("Disconnected from the server!");
            });
            // Keep the console window open
            Console.ReadLine();
        }
    }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Quobject.SocketIoClientDotNet.Client
Namespace DemoApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Connect to the Socket.IO server
			Dim socket = IO.Socket("http://localhost:3000")
			' Listen for the "connect" event
			socket.On(Socket.EVENT_CONNECT, Sub()
				Console.WriteLine("Connected to the server!")
				' Emit a message to the server
				socket.Emit("message", "Hello from C# client!")
				' Listen for messages from the server
				socket.On("message", Sub(data)
					Console.WriteLine("Message from server: " & data)
				End Sub)
			End Sub)
			' Listen for the "disconnect" event
			socket.On(Socket.EVENT_DISCONNECT, Sub()
				Console.WriteLine("Disconnected from the server!")
			End Sub)
			' Keep the console window open
			Console.ReadLine()
		End Sub
	End Class
End Namespace
VB   C#

Code Explanation

In the snippet, we first create a Socket.IO client instance/sender by calling IO.Socket("https://localhost:3000"), which connects to the local server running on port 3000 on the client machine.

Upon successful connection (Socket.EVENT_CONNECT), we print a message indicating that we are connected to the server.

Then, we emit a message from a client to the server using a socket.Emit("message", "Hello from C# client!"). This sends a message with the content "Hello from C# client!" to the Server.

Next, we listen for messages from the server by registering a callback for the "message" event using socket.On("message", (data) => { ... }). When the server sends a "message" event, the callback function is invoked, and we print the received message to the console.

If the connection to the server is disconnected from the client (Socket.EVENT_DISCONNECT), we print a message indicating disconnection.

Finally, the Console.ReadLine() method keeps the console window open so that the program doesn't exit immediately after execution. This allows us to see the output and ensures that the program doesn't terminate prematurely.

Screenshot of the code

Socket io .NET (How It Works For Developers): Figure 4 - Sample code

HTTP long-polling

Long-polling is a technique used in web development that employs a library to send messages between a client (usually a web browser) and a server. It enables real-time communication by triggering events on the server, which can then be received by the client without the need for continuous polling. This method is particularly useful for applications requiring immediate updates, such as chat applications or stock tickers.

Socket io .NET (How It Works For Developers): Figure 5 - HTTP long-polling

Web Sockets

WebSocket facilitates bi-directional communication by establishing full-duplex communication channels over a single TCP connection. This protocol enables real-time interaction between a client, typically a web browser, and a server, empowering both parties to asynchronously exchange messages.

Establishing WebSocket Communication

The client sends a WebSocket handshake request to the server, indicating its desire to establish a WebSocket connection. Upon receiving the handshake request, the server responds with a WebSocket handshake response, indicating that the connection has been successfully established. The Messages sent over the WebSocket connection can be in any format (e.g., text or binary) and can be sent and received asynchronously.

Web Transport

Web Transport, as a cutting-edge protocol, introduces additional features to enhance web communication beyond the limitations of traditional protocols like TCP and UDP. By leveraging UDP and QUIC, it addresses the shortcomings of its predecessors, making it more user-friendly and efficient. For users, this translates to reduced latency and improved congestion control, ultimately providing a smoother and more responsive web experience. Moreover, Web Transport offers better security measures, ensuring safer data transmission compared to TCP. With these advancements, Web Transport mitigates the time-consuming aspects of data transfer, optimizing the overall performance for both clients and servers.

Here's a basic example of how Web Transport can be used in a web application:

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The WebSocket URI
            string uri = "wss://echo.websocket.org";
            // Creating a new WebSocket connection
            using (ClientWebSocket webSocket = new ClientWebSocket())
            {
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                Console.WriteLine("Connected to the server");
                // Sending data over the WebSocket
                byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
                await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
                Console.WriteLine("Data sent to the server");
                // Receiving data from the WebSocket
                byte[] receiveBuffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                byte[] data = new byte[result.Count];
                Array.Copy(receiveBuffer, data, result.Count);
                Console.WriteLine("Received data: " + BitConverter.ToString(data));
            }
        }
    }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The WebSocket URI
            string uri = "wss://echo.websocket.org";
            // Creating a new WebSocket connection
            using (ClientWebSocket webSocket = new ClientWebSocket())
            {
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                Console.WriteLine("Connected to the server");
                // Sending data over the WebSocket
                byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
                await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
                Console.WriteLine("Data sent to the server");
                // Receiving data from the WebSocket
                byte[] receiveBuffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                byte[] data = new byte[result.Count];
                Array.Copy(receiveBuffer, data, result.Count);
                Console.WriteLine("Received data: " + BitConverter.ToString(data));
            }
        }
    }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			' The WebSocket URI
			Dim uri As String = "wss://echo.websocket.org"
			' Creating a new WebSocket connection
			Using webSocket As New ClientWebSocket()
				Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
				Console.WriteLine("Connected to the server")
				' Sending data over the WebSocket
				Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
				Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
				Console.WriteLine("Data sent to the server")
				' Receiving data from the WebSocket
				Dim receiveBuffer(1023) As Byte
				Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
				Dim data(result.Count - 1) As Byte
				Array.Copy(receiveBuffer, data, result.Count)
				Console.WriteLine("Received data: " & BitConverter.ToString(data))
			End Using
		End Function
	End Class
End Namespace
VB   C#

In this example, we first create a new WebTransport connection to a server using a WebSocket URL (wss://echo.websocket.org). Then, we create a bidirectional stream over the connection and send some data ([1, 2, 3, 4]) over the stream. Finally, we read data from the stream and log it to the console.

Output of the above code

When you run the application with the WebSocket echo server, the output should look something like this:

Socket io .NET (How It Works For Developers): Figure 6 - Console output for WebTransport connection using a WebSocket URL.

Advantages of Web Transport

Modern Alternative: Web Transport provides a modern alternative to traditional web communication protocols like TCP and UDP.

Efficient Data Transfer: It offers efficient data transfer by leveraging multiplexed streams and advanced features.

High Performance: Well-suited for building high-performance web applications that demand low latency and reliable data transfer.

Multiplexed Streams: Supports multiplexed streams, allowing multiple streams of data to be sent and received simultaneously over a single connection.

Innovation: As web developers continue to adopt Web Transport, we can expect to see more innovation in web communication protocols.

Improved User Experience: Adoption of Web Transport can lead to improved user experiences on the web due to faster and more reliable data transfer.

Introduction of the IronPDF Library

IronPDF is a comprehensive .NET PDF library specifically designed for developers working with C#. This powerful tool allows developers to effortlessly create, manipulate, and read PDF files within their applications. With IronPDF, developers can generate PDF documents from HTML strings, HTML files, and URLs, making it highly versatile for various use cases. Additionally, IronPDF offers advanced PDF editing features such as adding headers, footers, watermarks, and much more. Its seamless integration into C# projects via the NuGet package manager simplifies the process of working with PDF files, streamlining development and enhancing productivity.

Socket io .NET (How It Works For Developers): Figure 7 - IrpnPDF for .NET: The C# PDF Library

Install with NuGet Package Manager

Install IronPDF in Visual Studio or from the command line using the NuGet Package Manager. In Visual Studio, go to the console:

  • Tools -> NuGet Package Manager -> Package Manager Console
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

IronPDF code example

Here's a simple example using IronPDF to convert bits Data into a PDF File, Call the GeneratePDF method in Main method and pass the data as parameter that we had in above example

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo 
{
 class Program
 {
     static async Task Main(string[] args)
     {
         // The WebSocket URI
         string uri = "wss://echo.websocket.org";
         // Creating a new WebSocket connection
         using (ClientWebSocket webSocket = new ClientWebSocket())
         {
             await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
             Console.WriteLine("Connected to the server");
             // Sending data over the WebSocket
             byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
             await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
             Console.WriteLine("Data sent to the server");
             // Receiving data from the WebSocket
             byte[] receiveBuffer = new byte[1024];
             WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
             byte[] data = new byte[result.Count];
             Array.Copy(receiveBuffer, data, result.Count);
             Console.WriteLine("Received data: " + BitConverter.ToString(data));
              // Data to Generate in PDF File
              string pdfData = BitConverter.ToString(data);
              PDFGenerator.GeneratePDF(pdfData);
         }
     }
 }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo 
{
 class Program
 {
     static async Task Main(string[] args)
     {
         // The WebSocket URI
         string uri = "wss://echo.websocket.org";
         // Creating a new WebSocket connection
         using (ClientWebSocket webSocket = new ClientWebSocket())
         {
             await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
             Console.WriteLine("Connected to the server");
             // Sending data over the WebSocket
             byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
             await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
             Console.WriteLine("Data sent to the server");
             // Receiving data from the WebSocket
             byte[] receiveBuffer = new byte[1024];
             WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
             byte[] data = new byte[result.Count];
             Array.Copy(receiveBuffer, data, result.Count);
             Console.WriteLine("Received data: " + BitConverter.ToString(data));
              // Data to Generate in PDF File
              string pdfData = BitConverter.ToString(data);
              PDFGenerator.GeneratePDF(pdfData);
         }
     }
 }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
 Friend Class Program
	 Shared Async Function Main(ByVal args() As String) As Task
		 ' The WebSocket URI
		 Dim uri As String = "wss://echo.websocket.org"
		 ' Creating a new WebSocket connection
		 Using webSocket As New ClientWebSocket()
			 Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
			 Console.WriteLine("Connected to the server")
			 ' Sending data over the WebSocket
			 Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
			 Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
			 Console.WriteLine("Data sent to the server")
			 ' Receiving data from the WebSocket
			 Dim receiveBuffer(1023) As Byte
			 Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
			 Dim data(result.Count - 1) As Byte
			 Array.Copy(receiveBuffer, data, result.Count)
			 Console.WriteLine("Received data: " & BitConverter.ToString(data))
			  ' Data to Generate in PDF File
			  Dim pdfData As String = BitConverter.ToString(data)
			  PDFGenerator.GeneratePDF(pdfData)
		 End Using
	 End Function
 End Class
End Namespace
VB   C#

PDF Generation Class code

using IronPdf;
namespace SocketIO.Demo
{
    public class PDFGenerator
    {
        public static void GeneratePDF(string data)
        {
          IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
          Console.WriteLine("PDF Generating Started...");
      // Instantiate Renderer
          var renderer = new ChromePdfRenderer();
          Console.WriteLine("PDF Processing ....");
          var pdf = renderer.RenderHtmlAsPdf(data);
          string filePath = "Data.pdf";
          pdf.SaveAs(filePath);
          Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
        }
    }
}
using IronPdf;
namespace SocketIO.Demo
{
    public class PDFGenerator
    {
        public static void GeneratePDF(string data)
        {
          IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
          Console.WriteLine("PDF Generating Started...");
      // Instantiate Renderer
          var renderer = new ChromePdfRenderer();
          Console.WriteLine("PDF Processing ....");
          var pdf = renderer.RenderHtmlAsPdf(data);
          string filePath = "Data.pdf";
          pdf.SaveAs(filePath);
          Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
        }
    }
}
Imports IronPdf
Namespace SocketIO.Demo
	Public Class PDFGenerator
		Public Shared Sub GeneratePDF(ByVal data As String)
		  IronPdf.License.LicenseKey = "Your-Licence-Key-Here"
		  Console.WriteLine("PDF Generating Started...")
	  ' Instantiate Renderer
		  Dim renderer = New ChromePdfRenderer()
		  Console.WriteLine("PDF Processing ....")
		  Dim pdf = renderer.RenderHtmlAsPdf(data)
		  Dim filePath As String = "Data.pdf"
		  pdf.SaveAs(filePath)
		  Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}")
		End Sub
	End Class
End Namespace
VB   C#

Output

Socket io .NET (How It Works For Developers): Figure 8 - Console Output using SOcket.IO and IronPDF

In the provided code, IronPDF is used to generate a PDF document from a hexadecimal string received over a WebSocket connection. The GeneratePDF method initializes IronPDF with a license key and uses its ChromePdfRenderer instance to render the hexadecimal string as HTML content into a PDF using the RenderHtmlAsPdf method. You may get your free license key from here. This PDF is then saved locally as "Data.pdf" using the SaveAs method. IronPDF's integration allows seamless conversion of dynamic WebSocket data into a structured PDF format, demonstrating its utility in transforming real-time data streams into archival documents.

PDF File generated

Socket io .NET (How It Works For Developers): Figure 9 - Output PDF generated using IronPDF

Conclusion

Utilizing Socket.IO with C# introduces numerous opportunities for real-time interactions with connected clients, extending beyond the realm of JavaScript and Node.js. Integrating tools like Socket.IO and IronPDF into your .NET projects can significantly enhance real-time communication and PDF handling capabilities. Socket.IO facilitates seamless real-time, bidirectional communication between clients and servers, while IronPDF offers robust features for creating and manipulating PDF documents effortlessly.

IronPDF to unlock its full potential, ensuring efficient and reliable PDF generation and manipulation in your C# applications.

< PREVIOUS
C# foreach with index (How It Works For Developers)
NEXT >
Junit Java (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >