using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
class SimpleHttpServer
{
public static async Task StartServerAsync()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening for connections on http://localhost:8080/");
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
// Display the request URL.
Console.WriteLine($"Received request for {request.Url}");
// Construct a response.
string responseString = "<HTML><BODY>Hello world!</BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
using (System.IO.Stream output = response.OutputStream)
{
await output.WriteAsync(buffer, 0, buffer.Length);
}
}
}
static async Task Main(string[] args)
{
await StartServerAsync();
}
}
引入命名空间:
System.Net: 提供网络通信功能。System.Text: 提供字符编码和解码功能。System.Threading.Tasks: 支持异步编程。SimpleHttpServer 类:
StartServerAsync,用于启动 HTTP 服务器。HttpListener:
HttpListener 实例,监听 http://localhost:8080/ 上的请求。listener.Start() 启动监听器。无限循环:
while (true) 循环持续处理客户端请求。await listener.GetContextAsync() 获取请求上下文。处理请求:
response.OutputStream 发送响应数据。Main 方法:
StartServerAsync 方法启动服务器。上一篇:c# file
下一篇:c# byte 转string
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站