Socket IO Integration in ASP.NET Core

In this article, we will learn about how to integrate socket IO in ASP.NET Core.

Step 1:

Open Microsoft Visual Studio and create click on Create new Project, It will show a list of applications in these choose ASP.NET Core Empty option to create a project as follows.

Give appropriate name to project and uncheck the checkbox for Configure for HTTPS, now click on create button.

Step 2:

Add a WebSocket in the Configure method of Startup.cs Class.

Add following code in Startup.cs class:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

namespace Socket_Integration
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            var wsOption = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120) };
            app.UseWebSockets(wsOption);
            app.Use(async (context, next) =>
            {
                if (context.Request.Path == "/send")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
                        {
                            await send(context, webSocket);
                        }

                    }
                    else {
                        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                    
                }
            });

        }
        [HttpGet("/ws")]
        private async Task send(HttpContext context,WebSocket webSocket) 
        {
            
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None);
            if (result != null) 
            {
                while (!result.CloseStatus.HasValue)
                {
                    string msg = Encoding.UTF8.GetString(new ArraySegment<byte>(buffer, 0, result.Count));
                    Console.WriteLine($" Client Says : {msg}");
                    await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes($"Server Says {DateTime.UtcNow:f}")), result.MessageType, result.EndOfMessage, System.Threading.CancellationToken.None);
                    result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),System.Threading.CancellationToken.None);
                    Console.WriteLine(result);

                }
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, System.Threading.CancellationToken.None);
        }
    }
}

Here, KeepAliveInterval is used for how to frequently send “ping” frames to the client, to ensure proxies to keep the connection open.

The size of the buffer used to receive data.

When we want to transfer a message from server to client or client to server, then we need to call the AcceptWebSocketAsync method to upgrades the TCP connection to a WebSocket connection and it gives us a WebSocket object.

Step 3 :

now right-click on solution and select add option to add  new project in solution as follows:

and select Console application from add new project window.

Add name for Project. After that right-click on a project, it will show an option for managing NuGet packages.

Step 4:

Install System.Net.WebSockets.Client package into the project.

Step : 5:

After installing the package add the following code into Program.cs class in Ws_Client project.

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ws_Cient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Press enter to Continue........");
            Console.ReadLine();

            using (ClientWebSocket client = new ClientWebSocket())
            {
                Uri serviceuri = new Uri("ws://localhost:5000/send");
                var cTs = new CancellationTokenSource();
                cTs.CancelAfter(TimeSpan.FromSeconds(120));
                try 
                {
                    await client.ConnectAsync(serviceuri, cTs.Token);
                    var n = 0;
                    while (client.State == WebSocketState.Open)
                    {
                        Console.WriteLine("Enter message to send :");
                        string message = Console.ReadLine();
                        if (!string.IsNullOrEmpty(message))
                        {
                            ArraySegment<byte> byteTosend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
                            await client.SendAsync(byteTosend, WebSocketMessageType.Text, true, cTs.Token);
                            var responseBuffer = new byte[1024];
                            var offSet = 0;
                            var packet = 1024;
                            while (true)
                            {
                                ArraySegment<byte> byteToReceive = new ArraySegment<byte>(responseBuffer, offSet, packet);
                                WebSocketReceiveResult response = await client.ReceiveAsync(byteToReceive, cTs.Token);
                                var responsemessage = Encoding.UTF8.GetString(responseBuffer, offSet, response.Count);
                                Console.WriteLine(responsemessage);
                                if (response.EndOfMessage)
                                    break;
                            }
                        }
                    }
                }
                catch (WebSocketException ex) 
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.ReadLine();
        }
    }
}

Here, the serviceuri  call HttpGet send method which is in Socket_Integration and send the message to server.

OUTPUT:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories