.NET Core控制台应用创建WebSocket服务器及Microsoft.AspNetCore.WebSockets使用咨询
Hey Andy, great questions! Let's dive right in—you absolutely can build a .NET Core console app that hosts a WebSocket server using the Microsoft.AspNetCore.WebSockets NuGet package, and we can keep it lean without the heavy ASP.NET Core dependency injection setup you might have seen in other guides. Here's how to do it step by step:
1. Core Setup: Create the Console Project & Install Dependencies
First, create a new .NET Core console project (use .NET 6+ for cleaner top-level statements):
dotnet new console -n WebSocketConsoleServer cd WebSocketConsoleServer
Next, install the required .NET Core-compatible NuGet packages—no full .NET Framework dependencies needed:
dotnet add package Microsoft.AspNetCore.WebSockets dotnet add package Microsoft.AspNetCore
2. Implement the WebSocket Server Logic
Replace the contents of Program.cs with this code. I’ll break down the key parts below:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using System.Net.WebSockets; using System.Text; // Build a minimal ASP.NET Core host (we only need the HTTP pipeline for WebSockets) var webHost = WebHost.CreateDefaultBuilder(args) // Specify the URL your server will listen on .UseUrls("http://localhost:5000") .Configure(app => { // Enable the WebSockets middleware—this is the core component app.UseWebSockets(); // Map a specific endpoint for WebSocket connections (clients connect to ws://localhost:5000/ws) app.Map("/ws", async context => { // Reject any non-WebSocket requests if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.WriteAsync("This endpoint only accepts WebSocket connections."); return; } // Accept the WebSocket connection from the client using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); Console.WriteLine("Client connected successfully."); var buffer = new byte[1024 * 4]; // Buffer for receiving incoming message bytes WebSocketReceiveResult result; // Listen for messages until the client closes the connection do { result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); // Convert received bytes to a human-readable string var receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count); Console.WriteLine($"Received message: {receivedMessage}"); // Echo the message back to the client (replace this with your custom business logic) var responseBytes = Encoding.UTF8.GetBytes($"Server echo: {receivedMessage}"); await webSocket.SendAsync( new ArraySegment<byte>(responseBytes, 0, responseBytes.Length), result.MessageType, result.EndOfMessage, CancellationToken.None); } while (!result.CloseStatus.HasValue); // Clean up the connection properly await webSocket.CloseAsync( result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); Console.WriteLine("Client disconnected."); }); }) .Build(); // Start the server and keep it running await webHost.RunAsync();
Key Parts Explained:
- Minimal ASP.NET Core Host: We use
WebHost.CreateDefaultBuilderto spin up a lightweight HTTP server. This is required becauseMicrosoft.AspNetCore.WebSocketsrelies on the ASP.NET Core pipeline, but we don’t need any MVC/Razor features. - WebSocket Middleware:
app.UseWebSockets()enables the WebSocket protocol handling for your server. - Endpoint Mapping:
app.Map("/ws")defines the path clients will connect to (usews://localhost:5000/wsin your client tool). - Connection Handling: The code accepts connections, listens for incoming messages, echoes them back, and cleans up when the connection closes.
3. Test the Server
To test your server quickly, use a tool like wscat (a Node.js-based WebSocket client):
- Install wscat:
npm install -g wscat - Connect to your server:
wscat -c ws://localhost:5000/ws - Send a message—you’ll see it echoed back, and the console server will log the incoming message.
Additional Tips
- Error Handling: Add try/catch blocks around the receive/send logic to handle unexpected disconnections gracefully.
- Logging: Add built-in ASP.NET Core logging to get better visibility:
.ConfigureLogging(logging => logging.AddConsole()) - Scalability: For high-traffic scenarios, add concurrency handling (e.g.,
Task.WhenAll) to manage multiple connections at once.
内容的提问来源于stack exchange,提问作者Andy




