Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# httpserver

作者:噬血啸月   发布日期:2026-01-02   浏览:49

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();
    }
}

解释说明

  1. 引入命名空间:

    • System.Net: 提供网络通信功能。
    • System.Text: 提供字符编码和解码功能。
    • System.Threading.Tasks: 支持异步编程。
  2. SimpleHttpServer 类:

    • 包含一个静态异步方法 StartServerAsync,用于启动 HTTP 服务器。
  3. HttpListener:

    • 创建并配置 HttpListener 实例,监听 http://localhost:8080/ 上的请求。
    • 使用 listener.Start() 启动监听器。
  4. 无限循环:

    • 使用 while (true) 循环持续处理客户端请求。
    • 每次接收到请求时,使用 await listener.GetContextAsync() 获取请求上下文。
  5. 处理请求:

    • 打印请求的 URL。
    • 构造简单的 HTML 响应字符串。
    • 将响应字符串转换为字节数组,并设置响应的内容长度。
    • 使用 response.OutputStream 发送响应数据。
  6. Main 方法:

    • 调用 StartServerAsync 方法启动服务器。

上一篇:c# file

下一篇:c# byte 转string

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站