Working with WebSocket in Asp.Net Core

Hello, in today's article we will discuss WebSocket. But first, we need to look at communication in the server-client architecture. Web applications (client) communicate with the server over the HTTP protocol in a request/response manner. When the client requests something from the server, it opens a connection and sends a request. The server receives the request and processes it. The server then returns the response to the client. This traffic continues in this manner indefinitely. The client has to open a connection for every request. And if there's new information on the server that it can provide to the client, it can't send it directly to the client; instead, it has to wait for a request from the client.

This redundancy can consume the entire bandwidth. What's worse, this situation can nearly prevent the client from receiving a second piece of information. This can lead to significant losses in online financial transactions where real-time speed is crucial.

Web developers have been working for many years to overcome this limitation of HTTP and to enable more data transfer during any connection. But what they really wanted was to allow both the server and the client to send and receive data to each other without ever disconnecting the connection.

The solution that came to the rescue for this need was from the almost standardized HTML5. This new protocol introduced with HTML5 was WebSocket. WebSocket is a system that enables the internet to perform complex communication processes in real-time. WebSocket allows the client to establish a connection and maintain it as long as desired, enabling bi-directional data transfer, both receiving and sending.

WebSocket Example in Asp.Net Core

To use WebSocket, a basic script knowledge and intermediate knowledge in .Net Core is sufficient. The logic is straightforward.

First, we start by creating a core web application project named WebsocketUsage. Next, we add the AspNetCore.WebSockets package to the project via Nuget.

Install-Package Microsoft.AspNetCore.WebSockets -Version 2.2.1

Firstly, we will make the necessary settings in the Configure method of our application's Startup.cs class. We inform that we will use WebSocket at runtime. We will open the communication between the client and the server and check the messages of the incoming requests. Our goal is to capture the incoming message and say something in response.

Within the code, we first look at the Configure method. We notify the environment that we will use WebSocket with the UseWebSockets() function. As the application starts, we begin to listen to incoming requests. If this request is a WebSocket request (which should start with the ws:// protocol), we capture a socket object and call the Talk function (asynchronously, of course). If the incoming request is not made to the /nokya address, it continues to listen, waiting for the next message.

The Talk operation contains the necessary codes to print the message coming from the client to the terminal and to send back a randomly generated number value. The ReceiveAsync method is used to capture the message sent by the client. The first parameter of the method takes the incoming content into a Byte array. If the communication in between is open (checked with CloseStatus.HasValue), converting this byte content to string is sufficient. To send a message to the connected client over the socket, the SendAsync method is used. The traffic works with byte arrays, so UTF8-based Encoding mechanisms are used for string operations.

In Program.cs, we set the port we will use. We will broadcast from http://localhost:5556, and our clients will be able to establish websocket-based communication using the ws://localhost:5556/nokya address.

In the sample project, we will communicate with the socket using JavaScript on the index.html page as the client. The content of the page we placed in the wwwroot folder is as follows.

In our code, the action is triggered when the btnConnect button is pressed. As can be seen, a WebSocket object is created. The address used is ws://localhost:5556/nokya. Note that the address starts with 'ws'. Several events are defined for the created WebSocket object: when the connection is opened, closed, when a message is received from the server, or when an error occurs. To send a message to the server, the send function of the WebSocket object is used.

You can debug the project and see the results for yourself. I hope it has been helpful.

Source Code

Resources Used: