DEV Community

Cover image for Support for WebSocket in CodeBehind 4.1
Elanat Framework
Elanat Framework

Posted on

Support for WebSocket in CodeBehind 4.1

Introduction

WebSockets are a powerful protocol for enabling real-time communication between clients and servers. After several weeks of continuous efforts, we have added support for the WebSocket protocol in the CodeBehind framework. The WebSocket structure has been integrated into WebForms Core technology. In order to integrate WebSocket into the WebForms Core technology, we have changed or rewritten the created WebSocket structure several times. The WebSocket structure we have created is completely automatic and very easy to use. We are proud that the Code Behind framework and Web Forms Core technology enable the use of real-time structure.

With the integration of the WebSocket protocol into the WebForms Core technology, from now on you can broadcast Action Control data to all or some of the WebSockets. This feature provides developers with powerful real-time capabilities not found in most competing frameworks.

WebForms Core is a new high-level technology in the web platform that returns the current approach of the web from client to server. WebForms Core has a user-friendly structure that supports Drag-and-Drop for UI design. Using WebForms Core enables web development companies to save 70-85% on their product development time. This magic allows them to take full advantage of the most modern web architecture without spending a lot of money.

Version 4.1

As we mentioned earlier, in this version we added support for the WebSocket protocol in the CodeBehind core and the WebForms Core technology. In this version, the WebFormsJS library has also been updated to version 1.7 and the PostBack and GetBack methods were improved, and the structure of inserting and deleting events was also completely rewritten.

WebSocket data sending based on form data submission

The Elanat team has implemented another revolutionary idea, allowing WebSocket data to be sent via form submit. In this method, a WebSocket connection is first established and then the data is sent one after the other without the need for a server response. This revolutionary initiative allows developers to easily create real-time systems.

Example of sending data:

The following example shows how to send data. As you can see, the View below is a simple HTML page for submitting data to the server. To specify that data is sent via the WebSocket protocol, the usewebsocket attribute is added to the form tag. There are other ways to specify that data is sent via the WebSocket protocol, which we will discuss below.

Note: In the CodeBehind framework and WebForms Core Technology, data sent by WebSocket is sent only via the POST method.

View

@page
@controller MyController
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket in WebForms Core Technology</title>
    <script type="text/javascript" src="/script/web-forms.min.js"></script>
</head>
<body>
    <form action="page.aspx" method="post" usewebsocket>
        Text
        <br>
        <textarea name="Textarea1"></textarea><br><br>
        <input type="submit" name="Button1" value="Send">
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Other methods to specify sending data under WebSocket

Apart from adding the usewebsocket attribute to the form tag, there are other ways to specify whether to send data over WebSocket. These methods are available in the WebForms class on the server in all three parts: controller, model and view.

  • Activation and deactivation form.UseWebSocket(Path)

Specifies a path for the permanent WebSocket connection. In fact, it specifies that this path should only send data through the WebSocket protocol.

  • Always form.EnableWebSocket(true) // or false

Using this method, we can enable and disable WebSocket.

  • Once form.EnableWebSocketOnce()

Enables WebSocket once and then disables it.

In the controller, the server response is sent to the client that made the WebSocket request. To show that the data is sent exactly like sending Form data through form submit. In the "Button1_Click" method, we have read the textarea text through Form data and returned it to the client in the server response.

Controller

using CodeBehind;

public partial class MyController : CodeBehindController
{
    public void PageLoad(HttpContext context)
    {
        if (context.Request.Form["Button1"].Has())
            Button1_Click(context);
    }

    private void Button1_Click(HttpContext context)
    {
        string Text = context.Request.Form["Textarea1"];

        WebForms form = new WebForms();

        form.AddTag(InputPlace.Tag("form"), "h4");
        form.SetText(InputPlace.Tag("h4", -1), "Your submitted text: " + Text);

        Control(form, true);
    }
}
Enter fullscreen mode Exit fullscreen mode

This implementation demonstrates how submitted text is retrieved from form data and returned via WebSocket, maintaining the familiar form submission paradigm while leveraging real-time communication benefits.

Ability to specify IDs for WebSockets

You can specify an ID for WebSocket connection requests; this will cause the broadcast to only occur on WebSockets with the ID.
The WebSocket ID can be specified in the controller, model, and view.

Example

private void Button1_Click(HttpContext context)
{
    string Text = context.Request.Form["Textarea1"];

    WebForms form = new WebForms();

    form.AddTag(InputPlace.Tag("form"), "h4");
    form.SetText(InputPlace.Tag("h4", -1), "Your submitted text: " + Text);

    Control(form, true);

+   SetWebSocketId("page1"); 
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the ID "page1" is specified for the WebSocket connection.

Broadcast

Ability to broadcast data for WebSockets with filtering in controller, model and view

You can broadcast data based on the following criteria:

  • Filter by WebSocket id
  • Filter by WebSocket role name
  • Filter by session id
  • Do not broadcast for current session id

To filter by WebSocket id, you must have previously set the id with the SetWebSocketId method.
To filter by session id, you must have configured the session and cookie middleware in the Program.cs class.
To filter by Role name, you must have configured the UseRoleAccess middleware in the Program.cs class.

Broadcast methods:

  • Broadcast and BroadcastAsync
  • BroadcastForRole and BroadcastForRoleAsync
  • BroadcastForWebSocketId and BroadcastForWebSocketIdAsync
  • BroadcastForClientId and BroadcastForClientIdAsync

Example

string roleName= "member";
await BroadcastForRoleAsync(context, "Message", roleName, true);
Enter fullscreen mode Exit fullscreen mode

The last true is to prevent broadcasting to the current sending user.

Multiple connections

Due to the complexity of creating WebSocket connections, in most cases only one WebSocket connection is sufficient. However, Elanat has provided a powerful mechanism to create large numbers of WebSocket connections in the CodeBehind framework.

You don't have to do anything for multiple connections because on the client side, WebFormsJS automatically separates WebSocket requests based on the server request path.

WebSockets are determined on the client side based on the request path to the server.
You can also specify the WebSocket name on the server side in all three sections: Controller, Model, and View.

Maximum connections

At the end of the options file, two options have been added for WebSocket-related options.

One option is to specify the maximum number of WebSocket connections possible for each client, and the other is the buffer size for WebSocket connections.

Specifying the maximum number of connections helps manage server resources. WebSocket connections are queued; if a user attempts to establish a WebSocket connection from more than the maximum number of connections possible, the first active WebSocket is disconnected and removed from the queue, and a new connection is created.

You should determine the WebSocket buffer size according to the structure of the system you are designing. The buffer size should not be so small that it limits the sending and receiving of data, nor should it be so large that it overwhelms the limited resources of the server.

[CodeBehind options]; do not change order
view_path=wwwroot
move_view_from_wwwroot=true
rewrite_aspx_file_to_directory=false
access_aspx_file_after_rewrite=false
...
ignore_prefix_controller=.
ignore_suffix_controller=.
put_two_underlines_equal_to_dash_for_controller=false
set_default_pages=true
+max_web_socket_connections_per_client=3
+web_socket_buffer_size=4096
Enter fullscreen mode Exit fullscreen mode

Add WebSocket events in WebForms Core

To be able to establish a websocket connection, you can use the following methods in the WebForms class.

  • SetWebSocketEvent
  • SetWebSocketEventListener

The above methods establish a connection between the server and the client but do not send anything to the server.

Example:

WebForms form = new WebForms();

form.SetWebSocketEvent("<body>", HtmlEvent.OnLoad, "/ws3");

Control(form);
Enter fullscreen mode Exit fullscreen mode

In the example above, after the HTML page loads, a WebSocket connection is created to the path "/ws3".

Middleware for WebSocket

To enable developers to use the WebSocket protocol, we have added several middlewares to the CodeBehind framework.

List of middlewares:

UseCodeBehind similar to:
UseCodeBehindWebSockets
To access CodeBehind framework roles, use the middleware:
UseCodeBehindWebSocketsByRole

UseCodeBehind(true) similar to:
UseCodeBehindWebSocketsWithErrorHandling
To access CodeBehind framework roles, use the middleware:
UseCodeBehindWebSocketsWithErrorHandlingByRole

UseCodeBehindNextNotFound similar to:
UseCodeBehindWebSocketsNextNotFound
To access CodeBehind framework roles, use the middleware:
UseCodeBehindWebSocketsNextNotFoundByRole

UseCodeBehindRoute similar to:
UseCodeBehindRouteWebSockets
To access CodeBehind framework roles, use the middleware:
UseCodeBehindRouteWebSocketsByRole

UseCodeBehindRoute(true) similar to:
UseCodeBehindRouteWebSocketsWithErrorHandling
To access CodeBehind framework roles, use the middleware:
UseCodeBehindRouteWebSocketsWithErrorHandlingByRole

UseCodeBehindRouteNextNotFound similar to:
UseCodeBehindRouteWebSocketsNextNotFound
To access CodeBehind framework roles, use the middleware:
UseCodeBehindRouteWebSocketsNextNotFoundByRole

In the Program.cs class, you need to add the WebSocket middleware above the regular middleware. The WebSocket middleware options in the CodeBehind framework are identical to the UseWebSockets middleware options (the default in ASP.NET Core).

Example

Program.cs

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

SetCodeBehind.CodeBehindCompiler.Initialization(!app.Environment.IsDevelopment());

app.UseStaticFiles();

app.UseCodeBehindWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromMinutes(2) });

app.UseCodeBehind();

app.Run();
Enter fullscreen mode Exit fullscreen mode

In the above configuration, if a websocket request (with ws and wss protocols) is received on the server, the UseCodeBehindWebSockets middleware will respond to the request, and for regular HTTP and HTTPS requests, the UseCodeBehind middleware will respond.

Other improvements

In version 4.1, we completely rewrote the structure of inserting and removing events. In this version, all WebForms Core technology events are added and removed in addition to previous events and JavaScript events, without deleting previous ones.

In this version, parts of the PostBack and GetBack methods were improved. We also created a mechanism to add form input data to the action path so that the process of sending data in the PostBack method can also be done with the form submission via the GET method.

Conclusion

The release of CodeBehind 4.1 marks a significant step forward in real-time web development with seamless WebSocket integration in WebForms Core. This update empowers developers with:

Effortless Real-Time Communication: Built-in WebSocket support enables instant data broadcasting between clients and servers.

Smart Broadcasting & Filtering: Send targeted updates by WebSocket ID, role, or session, optimizing performance.

Simplified Development: Automatic connection handling and middleware support reduce boilerplate code.

Whether you're building live dashboards, chat applications, or dynamic UIs, CodeBehind 4.1 provides the tools to streamline development without sacrificing power.

πŸš€ Upgrade now and experience the future of real-time WebForms!

What will you build with WebSockets in CodeBehind? Share your ideas in the comments!

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay