Preface
In the .NET world, C# is a powerful programming language that is often used to build various types of applications, including web servers. Although in actual production environments, we usually use mature web server software (such as IIS, Kestrel, etc.), understanding how to build a simple web server from scratch using C# is very valuable for a deep understanding of HTTP protocol and network programming.
This article will guide you to write a simple web server using C# and include specific code implementations.
Step 1: Understanding the HTTP protocol
Before writing a web server, we need to have a basic understanding of the HTTP protocol. HTTP is a stateless, request- and response-based protocol. The client (such as a web browser) sends an HTTP request to the server, and the server processes the request and returns an HTTP response.
HTTP requests are composed of request lines, request headers and request bodies. The request line contains the request method (GET, POST, etc.), the request URL, and the HTTP protocol version. The request header contains additional information about the request, such as Host, User-Agent, etc. The request body contains data actually sent to the server and is usually used for POST requests.
HTTP response consists of a status line, a response header, and a response body. The status line contains the HTTP protocol version, status code, and status messages. The response header contains additional information about the response, such as Content-Type, Content-Length, etc. The response body contains the actual data returned by the server to the client.
Step 2: Create a TCP listener
In C#, we can use the TcpListener class to create a TCP listener to incoming HTTP requests. Here is a simple example code showing how to create a TCP listener and wait for a connection:
using System; using ; using ; using ; using ; using ; class SimpleWebServer { private const int Port = 8080; public static void Main() { TcpListener listener = new TcpListener(, Port); (); ($"Server started at http://localhost:{Port}/"); while (true) { TcpClient client = (); HandleClientAsync(client).Wait(); } } private static async Task HandleClientAsync(TcpClient client) { NetworkStream stream = (); StreamReader reader = new StreamReader(stream, Encoding.UTF8); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; try { // Read the request line string requestLine = await (); if ((requestLine)) return; ($"Received request: {requestLine}"); // parse the request line (for simplicity, only GET requests are processed here) string[] parts = (' '); if ( != 3 || parts[0] != "GET") { SendErrorResponse(writer, 400, "Bad Request"); return; } string path = parts[1]; if (path != "/") { SendErrorResponse(writer, 404, "Not Found"); return; } // Send a response SendResponse(writer, 200, "OK", "<html><body><h1>Hello, World!</h1></body></html>"); } catch (Exception ex) { ($"Error: {}"); SendErrorResponse(writer, 500, "Internal Server Error"); } finally { (); } } private static void SendResponse(StreamWriter writer, int statusCode, string statusMessage, string content) { ($"HTTP/1.1 {statusCode} {statusMessage}"); ("Content-Type: text/html; charset=UTF-8"); ($"Content-Length: {}"); (); (content); } private static void SendErrorResponse(StreamWriter writer, int statusCode, string statusMessage) { string content = $"<html><body><h1>{statusCode} {statusMessage}</h1></body></html>"; SendResponse(writer, statusCode, statusMessage, content); } }
This sample code creates a simple web server to listen8080
port. When the client connects to the server, the server reads the request line and returns the corresponding response based on the request path.
This is all about this article about using C# to write a web server. For more related C# Web server content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!