C# http服务器代码
时间: 2024-10-23 14:01:06 浏览: 13
C#实现HTTP协议迷你服务器(两种方法)
在C#中创建一个基本的HTTP服务器,可以使用内置的System.Net.HttpListener类。下面是一个简单的示例,展示了如何创建一个监听特定端口的HTTP服务器:
```csharp
using System;
using System.Net;
using System.IO;
class SimpleHttpServer
{
private HttpListener listener;
public void Start(int port)
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:" + port + "/");
listener.Start();
Console.WriteLine($"Server started on port {port}.\nPress any key to stop...");
Console.ReadKey();
// 接收并处理请求
while (true)
{
try
{
var context = listener.GetContext();
HandleRequest(context.Request, context.Response);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
listener.Stop();
}
private void HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
{
string requestBody = "";
using (var reader = new StreamReader(request.InputStream))
{
requestBody = reader.ReadToEnd();
}
string responseBody = "Hello from C# HTTP server!";
// 设置响应头和内容
response.ContentType = "text/plain";
response.StatusCode = 200; // OK
using (StreamWriter writer = new StreamWriter(response.OutputStream))
{
writer.Write(responseBody);
}
// 关闭输入流和输出流
request.InputStream.Close();
response.OutputStream.Close();
}
}
public static class Program
{
public static void Main(string[] args)
{
int port = 8080;
if (args.Length > 0)
{
port = Convert.ToInt32(args[0]);
}
SimpleHttpServer server = new SimpleHttpServer();
server.Start(port);
}
}
```
这个代码会监听指定的端口(默认8080),接收到所有GET请求,返回固定的字符串"Hello from C# HTTP server!"。你可以根据需要扩展HandleRequest方法来处理不同的请求。
阅读全文