-
Notifications
You must be signed in to change notification settings - Fork 0
CSharp
WebSockets enable real-time, bidirectional communication between a server and multiple clients. In C#, WebSockets are supported in ASP.NET Core, allowing efficient messaging in web applications.
β
How to create a WebSocket server using ASP.NET Core
β
How to create a WebSocket client in C#
β
How to send and receive messages
β
How to handle multiple clients
β
How to use WebSockets with HTML & JavaScript
We will create an ASP.NET Core Web API that supports WebSocket connections.
1οΈβ£ Open Visual Studio
2οΈβ£ Create a new ASP.NET Core Web API project
3οΈβ£ Select .NET 6+
4οΈβ£ Remove the default WeatherForecast
files
Modify Program.cs
to enable WebSockets:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Enable WebSockets
app.UseWebSockets();
app.Map("/ws", async (HttpContext context) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
using WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await HandleWebSocketConnection(webSocket);
}
else
{
context.Response.StatusCode = 400; // Bad Request
}
});
app.Run();
Create a new method HandleWebSocketConnection
to manage WebSocket communication.
using System.Net.WebSockets;
using System.Text;
async Task HandleWebSocketConnection(WebSocket webSocket)
{
var buffer = new byte[1024 * 4];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closed", CancellationToken.None);
break;
}
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {message}");
string response = $"Server: {message.ToUpper()}";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
- Receives messages from the client.
- Logs the message to the console.
- Sends back a response (converted to uppercase).
- Open Terminal in Visual Studio.
- Run the project with:
dotnet run
- The server starts at
ws://localhost:5000/ws
.
Now, let's create a C# WebSocket client to connect to the server.
1οΈβ£ Open Visual Studio
2οΈβ£ Create a new Console Application
3οΈβ£ Add System.Net.WebSockets for WebSocket support
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var client = new ClientWebSocket();
await client.ConnectAsync(new Uri("ws://localhost:5000/ws"), CancellationToken.None);
Console.WriteLine("Connected to WebSocket Server");
_ = Task.Run(async () =>
{
var buffer = new byte[1024];
while (client.State == WebSocketState.Open)
{
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received: {message}");
}
});
while (true)
{
string message = Console.ReadLine();
if (message.ToLower() == "exit") break;
byte[] bytes = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
}
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
Console.WriteLine("WebSocket closed");
}
}
-
Connects to
ws://localhost:5000/ws
- Reads messages from the console and sends them to the server
- Receives messages and displays them
- Start the WebSocket Server.
- Run the client in another terminal with:
dotnet run
- Type a message and press Enter.
- The server will respond with an uppercase message.
We can also connect a web client to our C# WebSocket server.
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<h2>WebSocket Chat</h2>
<div id="messages" style="border:1px solid black; padding:10px; height:200px; overflow:auto;"></div>
<input type="text" id="msg" placeholder="Enter message">
<button onclick="sendMessage()">Send</button>
<script>
const socket = new WebSocket("ws://localhost:5000/ws");
socket.onopen = () => console.log("Connected to server");
socket.onmessage = (event) => {
let messages = document.getElementById("messages");
messages.innerHTML += `<div>${event.data}</div>`;
};
function sendMessage() {
let msg = document.getElementById("msg").value;
socket.send(msg);
document.getElementById("msg").value = "";
}
</script>
</body>
</html>
- Open the file in a browser.
- Type a message and click Send.
- The server will respond, and the message will appear on the page.
πΉ Use HTTPS/WSS (wss://
) to secure connections.
πΉ Authenticate users (JWT tokens, API keys).
πΉ Limit message size to prevent DoS attacks.
πΉ Validate messages to prevent injection attacks.
πΉ Close inactive connections to free resources.
β
Built a WebSocket server in C# (ASP.NET Core).
β
Created a C# WebSocket client.
β
Implemented message handling & broadcasting.
β
Connected a JavaScript client.
β
Applied security best practices.