Implementing a Real-Time Chat Service with WebSocket and .NET
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.