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

c# httplistener

作者:缺爱╮不缺钙   发布日期:2025-11-30   浏览:61

using System;
using System.Net;

class HttpListenerExample
{
    static void Main(string[] args)
    {
        // 创建一个HttpListener实例
        HttpListener listener = new HttpListener();

        // 添加要监听的前缀,例如 http://localhost:8080/
        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 = System.Text.Encoding.UTF8.GetBytes(responseString);

                // 获取响应对象并设置响应内容
                HttpListenerResponse response = context.Response;
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // 停止监听
            listener.Stop();
        }
    }
}

解释说明:

  1. 创建 HttpListener 实例:我们首先创建了一个 HttpListener 对象,用于监听HTTP请求。
  2. 添加监听前缀:通过 listener.Prefixes.Add 方法指定要监听的URL前缀。这里我们监听的是 http://localhost:8080/
  3. 启动监听:调用 listener.Start() 方法启动监听。
  4. 等待传入请求:使用 listener.GetContext() 方法阻塞等待传入的HTTP请求。
  5. 处理请求:当有请求到达时,获取请求的URL并打印出来。
  6. 准备响应内容:构造一个简单的HTML字符串作为响应内容,并将其转换为字节数组。
  7. 发送响应:将响应内容写入到 response.OutputStream 中,并关闭输出流。
  8. 异常处理:捕获可能出现的异常并打印错误信息。
  9. 停止监听:在 finally 块中确保监听器在程序结束时正确停止。

这个示例展示了如何使用C#中的 HttpListener 类来创建一个简单的HTTP服务器,监听并响应客户端的请求。

上一篇:c# double转int

下一篇:c# post请求

大家都在看

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 中文站