Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing a Real-Time Chat Service with WebSocket and .NET

Tech Nov 25 12

Configure the server environment by installing the Fleck NuGet package, which provides a lightweight WebSocket implementation for .NET appilcations. The follownig console application manages connection lifecycle events and routes incoming payloads to all registered clients.

using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;

var activeClients = new List<IWebSocketConnection>();
var messenger = new WebSocketServer("ws://0.0.0.0:7181");

messenger.Start(client =>
{
    client.OnOpen = () =>
    {
        Console.WriteLine("[Session Initiated]");
        activeClients.Add(client);
    };

    client.OnClose = () =>
    {
        Console.WriteLine("[Session Terminated]");
        activeClients.Remove(client);
    };

    client.OnMessage = payload =>
    {
        Console.WriteLine($"Incoming: {payload}");
        foreach (var peer in activeClients.ToList())
        {
            peer.Send($"Broadcast: {payload}");
        }
    };
});

Console.WriteLine("Listening on ws://0.0.0.0:7181. Enter text to push to all sockets.");
string userCommand;
while ((userCommand = Console.ReadLine())?.ToLower() != "quit")
{
    if (string.IsNullOrEmpty(userCommand)) continue;

    foreach (var peer in activeClients.ToList())
    {
        peer.Send(userCommand);
    }
}

Construct a browser-based interface to interact with the messaging endpoint. The HTML structure captures user input, while the embedded JavaScript handles the WebSocket protocol handshake and event routing.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Terminal</title>
</head>
<body>
    <pre id="transcript"></pre>
    <form id="dispatchQueue">
        <input type="text" id="dataPayload" autocomplete="off" />
        <button type="submit">Transmit</button>
    </form>

    <script>
    (function bootstrap() {
        const outputArea = document.getElementById('transcript');
        const submitForm = document.getElementById('dispatchQueue');
        const textField = document.getElementById('dataPayload');
        const NativeWebSocket = window.WebSocket || window.MozWebSocket;

        outputArea.textContent += 'Requesting upstream link...\n';

        const stream = new NativeWebSocket('ws://localhost:7181/');

        stream.onopen = () => {
            outputArea.textContent += 'Channel opened successfully.\n';
        };

        stream.onmessage = (response) => {
            outputArea.textContent += `${response.data}\n`;
        };

        stream.onclose = () => {
            outputArea.textContent += 'Stream closed unexpectedly.\n';
        };

        submitForm.addEventListener('submit', (triggerEvent) => {
            triggerEvent.preventDefault();
            const rawText = textField.value.trim();
            if (rawText.length > 0) {
                stream.send(rawText);
                textField.value = '';
            }
        });

        window.activeStream = stream;
    })();
    </script>
</body>
</html>

Launch the host executable first to initialize the listening port. Once the service confirms it is awaiting connections, serve the web page through any static file server or integrated development environment. Text entered into either the terminal prompt or the browser input field will propagate across all active sessions in real time. Verify connectivity by monitoring the console output alongside the browser transcript area.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.