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

c# webserver

作者:任光阴风干ゝ影象   发布日期:2026-05-13   浏览:121

using System;
using System.Net;
using System.Text;

class SimpleWebServer
{
    public static void Main()
    {
        // 创建一个HttpListener实例,并添加前缀来监听特定的URL
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();
        Console.WriteLine("Listening for connections on http://localhost:8080/");

        try
        {
            while (true)
            {
                // 等待接收请求
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                // 获取请求的URL
                string url = request.Url.ToString();
                Console.WriteLine($"Received request for {url}");

                // 准备响应内容
                string responseString = "<html><body>Hello, World!</body></html>";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);

                // 设置响应头和内容长度
                HttpListenerResponse response = context.Response;
                response.ContentLength64 = buffer.Length;
                response.ContentType = "text/html";

                // 将响应内容写入输出流
                using (System.IO.Stream output = response.OutputStream)
                {
                    output.Write(buffer, 0, buffer.Length);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
        finally
        {
            listener.Stop();
        }
    }
}

解释说明:

  1. HttpListener:这是一个用于创建简单的HTTP服务器的类。它允许你监听特定的URL并处理传入的HTTP请求。
  2. Prefixes.Add:指定服务器监听的URL前缀。在这个例子中,服务器将监听http://localhost:8080/上的所有请求。
  3. GetContext():阻塞当前线程,直到接收到一个HTTP请求。接收到请求后,返回一个包含请求信息的HttpListenerContext对象。
  4. responseString:这是你要发送给客户端的HTML响应内容。
  5. ContentLength64 和 ContentType:设置响应的内容长度和类型。这里设置为text/html,表示返回的是HTML内容。
  6. output.Write:将响应内容写入到客户端的输出流中。

这个示例代码创建了一个简单的HTTP服务器,监听http://localhost:8080/,并对于每个请求返回一个简单的HTML页面。

上一篇:c# bouncycastle

下一篇:c# rectangle

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

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

Laravel 中文站