What is WebSocket?

WebSocket is a technology developed for providing real-time data streaming over the internet. It differs from the standard HTTP protocol used for data transmission. While HTTP involves making requests to the server and receiving responses, WebSocket establishes a continuous connection between the server and the client, allowing both parties to send data. This connection remains open between the browser and server, enabling the immediate transmission of data and preventing delays. This guarantees continuous and fast data streaming, making it an ideal choice for real-time applications. Therefore, WebSocket is commonly used in applications like real-time games, chat applications, financial tracking apps, and more.

This technology is part of the HTML5 standard and is supported by web browsers. It uses SSL/TLS encryption to secure connections. Open-source WebSocket libraries are also available, making it easily accessible for web developers. Moreover, it can be utilized in applications developed for smartphones and desktop devices. WebSocket enables fast and interactive data streaming and provides flexibility for developers. It supports the transmission and processing of large amounts of data, allowing for real-time updates and instant user responses. It offers flexibility for developers.

You can explore the documentation for ASP.Net Core here.

Sample C# Codes.

using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
class Program
{
    static async Task Main(string[] args)
    {
        var server = new HttpListener();
        server.Prefixes.Add("http://localhost:4180/");
        server.Start();
        
        while (true) 
        {
            var context = await server.GetContextAsync();
            if (context.Request.IsWebSocketRequest) 
            {
                var socket = await context.AcceptWebSocketAsync(subProtocol: null);
                var receiving = Task.Run(async (){
                        while (true) 
                        {
                        var buffer = new byte[1024];
                        var result = await socket.ReceiveAsync(new ArraySegment<byte(buffer),
                        CancellationToken.None);
                        Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, result.Count));
                        var message = Encoding
                        .UTF8
                        .GetBytes("Message received:"+ Encoding.UTF8.GetString(buffer, 0, result.Count));
                        
                        await socket.SendAsync(new ArraySegment<byte>(message),
                                                        WebSocketMessageType.Text,
                                                        true,
                                                        CancellationToken.None);
                }
                });
            }
        }
    }
}

Sample HTML Page

<html>

<head>
    <script>
        const socket = new WebSocket("http://localhost:4180");

        socket.onopen = function (event) {
            socket.send("Hello Server!");
        };

        socket.onmessage = function (event) {
            console.log("Message from server:", event.data);
        };
        socket.onerror = function (error) {
            console.error("WebSocket error: ", error);
        };
        socket.onclose = function (event) {
            console.log("WebSocket closed with code: ", event.code);
        }; 
    </script>
</head>

</html>


You may also like...

Leave a Reply

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